android.os.FileUriExposedException 自动安装APK报错 5分钟搞定Android 7.0+ FileProvider
开发自动更新安装APK的时候,遇到报错:
android.os.FileUriExposedException: file:///storage/emulated/0/xx/xx.apk exposed beyond app through Intent.getData();
不要慌,5分钟搞定它!
适配步骤:
1. 创建file_paths.xml文件,放到项目res/xml目录下;
名称"YourName"可以修改为你想要的;
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<!--files-path 代表:Context.getFilesDir().-->
<!--cache-path 代表:getCacheDir().-->
<!--extenal-path 代表:Environment.getExternalStorageDirectory().-->
<!--external-files-path 代表:Context#getExternalFilesDir(String) Context.getExternalFilesDir(null).-->
<!--external-cache-path 代表:Context.getExternalCacheDir().-->
<!--root-path 代表:系统根目录”/“-->
<!--表示Context.getFilesDir()目录或者其子目录。 示例 : /data/data/你的app包名/files/test1-->
<!--<files-path name="name1" path="test1" />-->
<!--表示Context.getCacheDir()目录或者其子目录。 示例 : /data/data/你的app包名/cache/test2-->
<!--<cache-path name="name2" path="test2" />-->
<!--表示Environment.getExternalStorageDirectory()目录或者其子目录。 示例 : /storage/emulated/0/test3-->
<!--<external-path name="name3" path="test3" />-->
<!--表示Context.getExternalFilesDir(null)目录或者其子目录。 示例 : /storage/emulated/0/Android/data/你的app包名/files/test4-->
<!--<external-files-path name="name4" path="test4" />-->
<!--表示Context.getExternalCacheDir()目录或者其子目录。 示例 : /storage/emulated/0/Android/data/你的app包名/cache/test5-->
<!--<external-cache-path name="myapk" path="test5" />-->
<!--表示 系统根目录”/“-->
<root-path name="YourName" path="." />
</paths>
2. 在AndroidManifest.xml文件中配置provider;
修改"你的app包名"为app的包名;
<application>
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="你的app包名.fileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
</application>
3. 修改代码中的Uri获取方式;
apkFile是要安装的目标apk文件;
String MIME_TYPE_APP = "application/vnd.android.package-archive";
// 通过Intent安装APK文件
Intent intents = new Intent(Intent.ACTION_VIEW);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Uri contentUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileProvider", apkFile);
intents.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intents.setDataAndType(contentUri, MIME_TYPE_APP);
} else {
intents.setDataAndType(Uri.parse("file://" + apkFile.toString()), MIME_TYPE_APP);
}
intents.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intents);
至此,自动安装APK已经完成;