Android--- Android 7.0 更新Apk或打开相册报错FileUriExposedException

在Android 7.0之后,有更新APK或者打开相册的时候,应用会抛出FileUriExposedException。原因是Android 7.0后不再允许在app中把file:// Uri暴露给其他app,否则应用会抛出FileUriExposedException。

这是FileUriExposedException官方文档:
https://developer.android.google.cn/reference/android/os/FileUriExposedException.html

这是FileProvider官方文档:
https://developer.android.google.cn/reference/android/support/v4/content/FileProvider.html

这是stack overflower关于该问题的讨论:
https://stackoverflow.com/questions/38200282/android-os-fileuriexposedexception-file-storage-emulated-0-test-txt-exposed

可以通过2种方法来解决:

方法1:通过FileProvider方式,通过以下步骤来解决这个问题:

步骤1:在清单文件中申明FileProvider
<provider  
         android:name="android.support.v4.content.FileProvider"  
         android:authorities="你的包名.fileprovider"  
         android:exported="false"  
         android:grantUriPermissions="true">  
         <meta-data  
             android:name="android.support.FILE_PROVIDER_PATHS"  
             android:resource="@xml/file_paths"/>  
</provider> 

android:name是固定写法。
android:authorities可自定义,是用来标识该provider的唯一标识,一般结合包名来保证authority的唯一性。
android:exported必须设置成 false,否则运行时会报错java.lang.SecurityException: Provider must not be exported 。
android:grantUriPermissions用来控制共享文件的访问权限。

步骤2:在项目中的src/res/xml中创建步骤1中resource所对应的文件(file_paths.xml)并编辑

src/res/xml/file_paths内容:

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path
        name="files_root"
        path="Android/data/你的包名/" />
    <external-path
        name="external_storage_root"
        path="." />
</paths>
步骤3:修改代码(更新APK)
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        Uri contentUri = FileProvider.getUriForFile(context, "你的包名.fileprovider", 文件File对象);
                        intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
                    } else {
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.setDataAndType(Uri.fromFile(文件File对象),
                                "application/vnd.android.package-archive");
                    }
                    context.startActivity(intent);

方法2:VmPolicy方式
在application中的oncreate()方法下面

       if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
            builder.detectFileUriExposure();
        }
    原文作者:HPD_黄霹雳
    原文地址: https://www.jianshu.com/p/90c81e7e74a3
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞