android 调用相机问题
问题
调用相机时
private static final int TAKE_PICTURE = 0;
Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
imageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "image.jpg"));
openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(openCameraIntent, TAKE_PICTURE);
可能会报以下错误
android.os.FileUriExposedException: file:///storage/emulated/0/cache.jpg exposed beyond app through ClipData.Item.getUri()
解决方法
使用FileProvider解决
1、先在src/main/res/xml创建file_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<paths>
<root-path name="root_path" path="."/>
<external-path path="Android/data/${applicationId}/"
name="camera_photos" />
</paths>
</resources>
2、在AndroidManifest.xml进行配置
<application>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
</application>
3、在原来调用相机的Activity中修改代码
private static final int TAKE_PICTURE = 0;
File file = new File("image.jpg");
Uri imageUri = FileProvider.getUriForFile(getApplicationContext(), BuildConfig.APPLICATION_ID+".provider", file);
Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(openCameraIntent, TAKE_PICTURE);
其他问题
另外要提一下,某些同学会在写file_paths.xml这一步中可能会不写<root-path>这一标签,但是如果去缺少这一标签可能会造成以下错误:
java.lang.IllegalArgumentException: Failed to find configured root that contains /image.jpg
这是共享SD卡时发生的错误,加上<root-path>这一标签就可以解决了。