從Android 7.0起,不在容許在app中把file://Uri暴露給其餘app,不然會拋出異常FileUriExposedException.android
由於谷歌認爲使用file://Uri存在必定的風險。bash
解決方案是使用FileProvider生成content://Uri來替代file://Uriapp
以install apk爲例ide
<application
...>
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.fileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
</application>
複製代碼
<?xml version="1.0" encoding="utf-8"?>
<paths>
<!-- path:須要臨時受權訪問的路徑(.表明全部路徑) name:訪問路徑名稱 -->
<external-path name="apk_path" path="." />
<!--須要什麼就添加什麼-->
<files-path name="name" path="path" /> <!--對應Context.getFilesDir()-->
<cache-path name="name" path="path" /> <!--對應 getCacheDir()-->
<external-path name="name" path="path" /> <!--對應Environment.getExternalStorageDirectory()-->
<external-files-path name="name" path="path" /> <!--對應 Context.getExternalFilesDir(String)-->
<external-cache-path name="name" path="path" /> <!--對應Context.getExternalCacheDir()-->
<external-media-path name="name" path="path" /> <!--對應Context.getExternalMediaDirs()-->
</paths>
複製代碼
7.0起版本install apk適配代碼ui
private void installApk(File file) {
Intent install = new Intent(Intent.ACTION_VIEW);
Uri uri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
// "包名.fileprovider"便是在清單文件中配置的authorities
uri = FileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID+".fileProvider", file);
// 給目標應用一個臨時受權
install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
} else {
uri = Uri.fromFile(file);
}
install.setDataAndType(uri, "application/vnd.android.package-archive");
install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// 執行意圖進行安裝
mContext.startActivity(install);
}
複製代碼