最近接手公司的apk更新迭代时发现每次下载完新版本跳转安装时apk就闪退
查看log发现问题FileUriExposedException,原因是Android不再允许在app中把file://Uri暴露给其他app,包括但不局限于通过Intent或ClipData 等方法。因此提出一下解决方案:
步骤一:在清单文件applicantion中添加如下代码:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="你的包名.fileProvider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
步骤二:在res的xml里新建file_paths.xml
file_paths.xml :
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path path="Android/data/你的包名/" name="files_root" />
<external-path path="." name="external_storage_root" />
</paths>
步骤三:修改跳转逻辑
String path 为安装包路径
private void installAPK(String path) {
Intent intent = new Intent(Intent.ACTION_VIEW);
//解决7.0更新安装闪退的问题
//判断是否是AndroidN以及更高的版本
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
File file = new File(path);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Uri contentUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileProvider", file);
intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
} else {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(Uri.parse("file://" + path),"application/vnd.android.package-archive");
}
_mActivity.startActivity(intent);
}