在安卓7.0以上机型,在使用
Uri uri=Uri.fromFile();
会报
android.os.FileUriExposedException: file:///storage/emulated/xxx
异常,比如拍照时,常用的写法是:
Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri imageUri = Uri.fromFile(file);
openCameraIntent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(openCameraIntent, _TAKEPHOTO);
但放在7.0以上系统就会报错了,原因我就不再讲了,详细可查一下7.0的更新内容,现在主要来提供一下简单的改进方法:
File file = new File(photoSavePath, photoSaveName);
Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
ContentValues contentValues = new ContentValues(1);
contentValues.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
Uri uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(openCameraIntent, _TAKEPHOTO);
} else {
Uri imageUri = Uri.fromFile(file);
openCameraIntent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(openCameraIntent, _TAKEPHOTO);
}
此方法只针对于对图片的处理,如果是对文件,比如更新app时,下载完app要自动进入安装界面,7.0以下的做法是:
Uri uri = Uri.fromFile(updateFile);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(uri, "application/vnd.android.package-archive");
pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
...
但在7.0以上会有上述同样的问题,改进方法,使用FileProvider:
1.新建xml/file_path.xml,如图:
<paths>
<external-path
name=""
path="" />
</paths>
一般用external-path即可满足需求,name为自定义名称,path为你真正的文件夹名称,比如我的app定义的文件夹名称为Demo,则可写成:
<paths>
<external-path
name="my_external_path"
path="Demo" />
</paths>
还可以叠加使用如:
<paths>
<external-path
name="my_external_path1"
path="Demo" />
<external-path
name="my_external_path2"
path="com.xx.demo" />
<external-path
name="my_external_path3"
path="Android/data/com.xx.demo/" />
</paths>
2.在AndroidManifest.xml的application标签下添加:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="你的包名"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_path" />
</provider>
3.代码中判断:
Uri uri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
uri = FileProvider.getUriForFile(getApplicationContext(), "你的包名", updateFile);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
} else {
uri = Uri.fromFile(updateFile);
}