94.android7.0 获取uri

链接:https://blog.csdn.net/lanxuan1993/article/details/81627436

借鉴:https://blog.csdn.net/qq_33505109/article/details/90405302

android7.0以后,使用Uri.fromFile会报FileUriExposedException异常,这是因为android7.0以后执行了更加严格的文件管理,要解决这一错误需要使用7.0新添加的FileProvide类,FileProvider官方文档:官方链接

报错原因:android7.0对于系统权限作了一些更改,为了提高私有文件的安全性,当我们在访问文件的时候,安卓禁止您的应用外部公开file://uri 

解决思路:需要在应用之间共享文件,那就少不了FileProvider类

 

1.在清单文件中添加provider内容

<application
    android:name=".AppApplication"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
 
    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="demo.exmple.com.emidemo.utils.FileProvider7"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />
    </provider>
</application>
 

2.在resource中新建xml文件夹,在res/xml/file_paths文件夹中新建以下内容

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <paths xmlns:android="http://schemas.android.com/apk/res/android">
 
        <root-path
            name="root"
            path="" />
        <files-path
            name="files"
            path="" />
 
        <cache-path
            name="cache"
            path="" />
 
        <external-path
            name="external"
            path="" />
 
        <external-files-path
            name="external_file_path"
            path="" />
        <external-cache-path
            name="external_cache_path"
            path="" />
    </paths>
</resources>

 

3.获取uri

public static Uri getUriForFile(Context context, File file) {
        Uri fileUri = null;
        if (Build.VERSION.SDK_INT >= 24) {
            fileUri = getUriForFile24(context, file);
        } else {
            fileUri = Uri.fromFile(file);
        }
        return fileUri;
    }
 
    public static Uri getUriForFile24(Context context, File file) {
        Uri fileUri = android.support.v4.content.FileProvider.getUriForFile(context,
                context.getPackageName() + ".utils.FileProvider7",
                file);
        return fileUri;
    }

另:androidx.core.content.FileProvider替换android.support.v4.content.FileProvider

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值