转载:https://www.icode9.com/content-4-619191.html
我们在APP升级的时候进行下载安装,却在Android 7.0及以上版本会报错
android.os.FileUriExposedException: file:///路径 exposed beyond app through Intent.getData()
我们可以借助FileProvider来解决这个问题
在项目的res文件夹下新建一个xml文件夹,在xml文件夹新建一个.xml文件
filepaths.xml
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
在AndroidManifest的Application标签下新增provider标签
<application
......
android:usesCleartextTraffic="true"
android:theme="@style/AppTheme">
<activity
.......
</activity>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.ice.AAAAA.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/filepaths"
/>
</provider>
</application>
当apk下载好之后启动安装
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Uri uri;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//记得修改com.xxx.fileprovider与androidmanifest相同
uri = FileProvider.getUriForFile(mContext,"com.ice.AAAAA.fileprovider",apkFile);
intent.setDataAndType(uri,"application/vnd.android.package-archive");
}else{
uri = Uri.parse("file://" + apkFile.toString());
}
intent.setDataAndType(uri, "application/vnd.android.package-archive");
mContext.startActivity(intent);