安卓获取uri 适配安卓各版本

一.安卓7.0以上系统

1.在AndroidManifest中配置

<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="${applicationId}.fileprovider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/update_paths" />
</provider>

2.在安卓res目录下配置device_filter.xml文件

文件内容如下:

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <root-path
        name="root"
        path="" />
</paths>

3.获取uri

/**
 * 根据文件路径获取uri
 * @param context
 * @param filepath
 * @return
 */
public static Uri getUri(Context context,String filepath){
    Uri u= null;
    try {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            u = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", new File(filepath));
        } else {
            u=Uri.parse("file://" + filepath);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return u;
}
/**
 * 根据文件获取uri
 * @param context
 * @param file
 * @return
 */
public static Uri getUri(Context context,File file){
    if(file==null){
        return null;
    }
    Uri u=null;
    if (Build.VERSION.SDK_INT >= 24) {
        if(context==null){
            return null;
        }
        u = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", file);
    } else {
        u=Uri.fromFile(file);
    }
    return u;
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值