适配Android N打开文件

1.在AndroidManifest.xml添加如下代码:

<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="app包名.fileProvider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>

注:exported的值必须为false

2.在res目录下创建xml文件夹,并新建一个file_paths.xml资源文件

3.在file_paths.xml中添加如下内容:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path path="Android/data/app包名/" name="files_root" />
    <external-path path="." name="external_storage_root" />

</paths>

4.调用,判断是Android7.0以下版本还是以上版本

//android获取一个用于打开图片文件的intent
public static Intent getImageFileIntent(Context context, String param) {
    Intent intent = new Intent("android.intent.action.VIEW");
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//判断是否为Android N版本
        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        Uri contentUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileProvider", new File(param));
        intent.setDataAndType(contentUri, "image/*");
    } else {
        Uri uri = Uri.fromFile(new File(param));
        intent.setDataAndType(uri, "image/*");
    }
    intent.addCategory("android.intent.category.DEFAULT");
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    return intent;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值