Android 7.0以上。应用间共享文件,禁止公开 file:// URI,如果一项包含文件 URI 的 intent 离开您的应用,则应用出现FileUriExposedException 异常。
android 7.0以上,拍照,安装app等需要做适配。
具体流程如下:
1、manifest中注册FileProvider,并在xml文件中指定需要共享的文件路径
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.myapplication.fileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"/> //需要共享的文件路径
</provider>
2.xml文件夹中添加file_paths
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path
name="external"
path="."/> //代表根目录context.getFilesDir()
<files-path
name="files"
path="."/> //代表根目录Environment.getExternalStorageDirectory()
</paths>
3.使用共享文件的地方使用FileProvider类的getUriForFile修改URI,并调用addFlags添加授权
如下载app:
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, "authorities", apkFile); //authorities就是provider里声明的authorities
intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
} else {
intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
startActivity(intent);
网友评论