Android系統7.0以上遇到exposed beyond app through ClipData.Item.getUri
Android7.0呼叫相機時出現新的錯誤:
android.os.FileUriExposedException:file:///storage/emulated/0/xxx exposed beyond app throughClipData.Item.getUri()
android.os.FileUriExposedException:file:///storage/emulated/0/Download/appName-2.3.0.apk exposed beyond appthrough Intent.getData()
解決方法
1、在AndroidManifest.xml中新增如下程式碼
<provider
android:name=
"android.support.v4.content.FileProvider"
android:authorities=
"app的包名.fileProvider"
android:grantUriPermissions=
"true"
android:exported=
"false">
<meta-data
android:name=
"android.support.FILE_PROVIDER_PATHS"
android:resource=
"@xml/file_paths" />
</provider>
注意:
authorities:app的包名.fileProvider
grantUriPermissions:必須是true,表示授予 URI 臨時訪問許可權
exported:必須是false
resource:中的@xml/file_paths是我們接下來要新增的檔案
2、在res目錄下新建一個xml資料夾,並且新建一個file_paths的xml檔案(如下圖)
3、開啟file_paths.xml檔案新增如下內容
<?xml version=
"1.0" encoding=
"utf-8"?>
<paths>
<external-path path=
"Android/data/app的包名/" name=
"files_root" />
<external-path path=
"." name=
"external_storage_root" />
path:需要臨時授權訪問的路徑(.代表所有路徑)
name:就是你給這個訪問路徑起個名字
4、修改程式碼適配Android N
Intent intent =
new Intent(Intent.ACTION_VIEW);
//判斷是否是AndroidN以及更高的版本
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Uri contentUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID +
".fileProvider", apkFile);
intent.setDataAndType(contentUri,
"application/vnd.android.package-archive");
}
else {
intent.setDataAndType(Uri.fromFile(apkFile),
"application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
startActivity(intent);
微博分享遇到以下錯誤:
問題file:///storage/emulated/0/photo.jpegexposed beyond app through ClipData.Item.getUri
解決方法:
在Application.onCreate加入如下程式碼
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
builder.detectFileUriExposure();
從Android 7.0開始,一個應用提供自身檔案給其它應用使用時,如果給出一個file://格式的URI的話,應用會丟擲FileUriExposedException。這是由於谷歌認為目標app可能不具有檔案許可權,會造成潛在的問題。所以讓這一行為快速失敗。因此以上兩種方法可以解決問題。