Android 7.0行为变更 FileUriExposedException解决方案

当我们开发关于【在应用间共享文件】相关功能的时候,在Android 7.0上经常会报出此运行时异常,那么Android 7.0以下没问题的代码,为什么跑到Android 7.0+的设备上运行就出问题了呢?,这主要来自于Android 7.0的一项【行为变更】!

对于面向 Android 7.0 的应用,Android 框架执行的 StrictMode API 政策禁止在您的应用外部公开 file:// URI。如果一项包含文件 URI 的 intent 离开您的应用,则应用出现故障,并出现 FileUriExposedException 异常。

《Android 7.0行为变更 FileUriExposedException解决方案》 Paste_Image.png

要在应用间共享文件,您应发送一项 content:// URI,并授予 URI 临时访问权限。进行此授权的最简单方式是使用 FileProvider 类。

FileProvider 类的用法:

第一步:为您的应用定义一个FileProvider清单条目,这个条目可以声明一个xml文件,这个xml文件用来指定应用程序可以共享的目录。

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapp">
    <application
        ...>
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.example.myapp.fileprovider"
            android:grantUriPermissions="true"
            android:exported="false">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/filepaths" />
        </provider>
        ...
    </application>
</manifest>```
在这段代码中, android:authorities 属性应该是唯一的,推荐使用【应用包名+fileprovider】,推荐这样写 android:authorities=”${applicationId}.file_provider”,可以自动找到应用包名。 
meta-data标签指定了一个路径,这个路径使用resource指定的xml文件来指明是那个路径: 
xml文件如下:

<?xml version=”1.0″ encoding=”utf-8″?>
<paths>
<external-files-path name=”bga_upgrade_apk” path=”upgrade_apk” />
</paths>“`
Uri的获取方式也要根据当前Android系统版本区分对待:

   File dir = getExternalFilesDir("user_icon");
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            icon_path = FileProvider.getUriForFile(getApplicationContext(),
                    "com.mqt.android_headicon_cut.file_provider", new File(dir, TEMP_FILE_NAME));
        } else {
            icon_path = Uri.fromFile(new File(dir, TEMP_FILE_NAME));
        }```
这样问题就解决了。贴上一个安装apk适配7.0的例子:[http://blog.csdn.net/qq_27512671/article/details/70224978](http://blog.csdn.net/qq_27512671/article/details/70224978)
参考: [https://developer.android.google.cn/about/versions/nougat/android-7.0-changes.html#accessibility](https://developer.android.google.cn/about/versions/nougat/android-7.0-changes.html#accessibility) [https://developer.android.google.cn/training/secure-file-sharing/setup-sharing.html#DefineProvider](https://developer.android.google.cn/training/secure-file-sharing/setup-sharing.html#DefineProvider)
    原文作者:GB_speak
    原文地址: https://www.jianshu.com/p/6a1bbfae4ce8
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞