對於面向 Android 7.0 的應用,Android 框架執行的 StrictMode API 政策禁止在您的應用外部公開 file:// URI。如果一項包含文件 URI 的 intent 離開您的應用,則應用出現故障,並出現 FileUriExposedException 異常。
點擊查看鴻洋大神解析
適配方案
工具類
public class FileProvider7 {
/**
* 獲取文件uri 適配7.0
*/
public static Uri getUriForFile(Context context, File file) {
Uri fileUri = null;
if (Build.VERSION.SDK_INT >= 24) {
fileUri = FileProvider.getUriForFile(context, context.getPackageName() + ".android7.fileprovider", file);
} else {
fileUri = Uri.fromFile(file);
}
return fileUri;
}
/**
* apk安裝適配7.0
*/
public static Intent installAPK(Context context, File apkFile) {
Intent installIntent = new Intent(Intent.ACTION_VIEW);
installIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
setIntentDataAndType(context, installIntent, "application/vnd.android.package-archive", apkFile);
context.startActivity(installIntent);
return installIntent;
}
/**
* apk安裝intent適配7.0
*/
private static void setIntentDataAndType(Context context, Intent intent, String type, File apkfile) {
intent.setDataAndType(getUriForFile(context, apkfile), type);
if (Build.VERSION.SDK_INT >= 24) {
//添加這一句表示對目標應用臨時授權該Uri所代表的文件
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION|Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
}
}
}
AndroidManifest.xml配置
<application>
...
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.android7.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
</application>
res/xml/file_paths.xml配置
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<root-path name="root" path="" />
<files-path name="files" path="" />
<cache-path name="cache" path="" />
<external-path name="external" path="" />
<external-files-path name="external_file_path" path="" />
<external-cache-path name="external_cache_path" path="" />
</paths>
<root-path/> 代表設備的根目錄new File("/");
<files-path/> 代表context.getFilesDir()
<cache-path/> 代表context.getCacheDir()
<external-path/> 代表Environment.getExternalStorageDirectory()
<external-files-path>代表context.getExternalFilesDirs()
<external-cache-path>代表getExternalCacheDirs()
使用
Intent imageCaptureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File out = new File(imgPath);
Uri uri = FileProvider7.getUriForFile(activity, out);
imageCaptureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
imageCaptureIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
activity.startActivityForResult(imageCaptureIntent, requestCode);