Android N 上 安裝Apk時報錯:
android.os.FileUriExposedException: file:///storage/emulated/0/Download/appName-2.3.0.apk exposed beyond app through Intent.getData()
在網(wǎng)上找了一陣子,
解決方法如下:
1、在AndroidManifest.xml中添加如下代碼
<application……
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.xxx.saturn.apkfileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/apk_file_provider" />
</provider>
</application>
注意:
authorities:app的包名.apkfileprovider
grantUriPermissions:必須是true伪朽,表示授予 URI 臨時訪問權(quán)限
exported:必須是false
resource:中的@xml/file_paths是我們接下來要添加的文件
2轴咱、res路徑下新建xml文件添加如下文件(文件名為上面的apk_filr_provider)
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-cache-path name="newest_apk" path="" />
</paths>
path:需要臨時授權(quán)訪問的路徑(.代表所有路徑) (我這邊是沒有寫內(nèi)容,但是網(wǎng)上的一些朋友說不寫會報錯)
name:就是你給這個訪問路徑起個名字
3、在打開新下載的安裝包的地方修改代碼
Intent intent = new Intent();
intent.setAction(android.content.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, "com.iboxpay.saturn.apkfileprovider", file);
intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
} else {
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
}
startActivity(intent);
1朴肺、首先我們對Android N及以上做判斷窖剑;
2、然后添加flags戈稿,表明我們要被授予什么樣的臨時權(quán)限
3西土、以前我們直接 Uri.fromFile(apkFile)構(gòu)建出一個Uri,現(xiàn)在我們使用FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileprovider", apkFile);
4、BuildConfig.APPLICATION_ID直接是應(yīng)用的包名
加上寫的比較好的幾個鏈接
Android7.0須知--應(yīng)用間共享文件FileProvider鞍盗;
[Android 7.0 FileUriExposedException 解決需了,支持新浪微博](Android 7.0 FileUriExposedException 解決,支持新浪微博)般甲;
Android7.0拍照失敗FileUriExposedException,你的拍照代碼升級了嗎