Android 日常开发(48)android.os.FileUriExposedException最佳解决办法

前言

我之前在weex的问题合集里面讲过一次这种异常的处理办法不过当时时通过关闭android严苛模式的视角处理的。今天我们来深入sdk,看看这个问题的最佳解决方式

1.我们通过android developer官网搜索android.os.FileUriExposedException这个异常

The exception that is thrown when an application exposes a file:// Uri
to another app.

This exposure is discouraged since the receiving app may not have
access to the shared path. For example, the receiving app may not have
requested the Manifest.permission.READ_EXTERNAL_STORAGE runtime
permission, or the platform may be sharing the Uri across user profile
boundaries.

Instead, apps should use content:// Uris so the platform can extend
temporary permission for the receiving app to access the resource.

This is only thrown for applications targeting Build.VERSION_CODES#N
or higher. Applications targeting earlier SDK versions are allowed to
share file:// Uri, but it’s strongly discouraged.

Android 7.0在文件安全方面提出了更多要求,需要开发者做成额外的配置来明确需求。

2.解决方法
了解FileProvider类的使用

快速解决问题如下:
1.在清单文件里面配置


        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.xxx.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths" />
        provider>


<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <files-path name="filespath" path="/yourstoragefilepath/"  />
    <cache-path name="cachepath" path="path" />
    
    <external-path name="externalpath" path="path" />
    <external-files-path name="externalfilespath" path="path" />
    <external-cache-path name="externalcachepath" path="path" />
    <root-path name="rootpath" path="/storage/emulated/0/yourdir/" />
paths>

两种文件获取方式的区别:
不使用FileProvider方式

	Uri uri=Uri.fromFile(new File(outPath));

使用FileProvider方式


Uri uri=FileProvider.getUriForFile(MergeActivity.this, "com.joe.fileprovider", new File(outPath));

使用外部应用打开文件:

	Intent intent = new Intent("android.intent.action.VIEW");
	intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
							intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION|Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
//	Uri uri=Uri.fromFile(new File(outPath));
	Uri uri=FileProvider.getUriForFile(MergeActivity.this, "com.joe.fileprovider", new File(outPath));

	intent.addCategory("android.intent.category.DEFAULT");

	intent.setDataAndType(uri, "video/mp4");
	startActivity(intent);

你可能感兴趣的:(Android 日常开发(48)android.os.FileUriExposedException最佳解决办法)