问题
When I try to capture a picture I have this error :
FATAL EXCEPTION: main android.os.FileUriExposedException: file:///storage/emulated/0/fname_1498727381241.jpg exposed beyond app through ClipData.Item.getUri() at android.os.StrictMode.onFileUriExposed(StrictMode.java:1799) at android.net.Uri.checkFileUriExposed(Uri.java:2346) at android.content.ClipData.prepareToLeaveProcess(ClipData.java:835) at android.content.Intent.prepareToLeaveProcess(Intent.java:9514) at android.content.Intent.prepareToLeaveProcess(Intent.java:9499) at android.app.Instrumentation.execStartActivity(Instrumentation.java:1525) at android.app.Activity.startActivityForResult(Activity.java:4403) at android.app.Activity.startActivityForResult(Activity.java:4362) at opteamit.com.belami.CommuniquerPartagerPhotosActivity$1.onClick(CommuniquerPartagerPhotosActivity.java:46) at android.view.View.performClick(View.java:6261) at android.view.View$PerformClick.run(View.java:23752) at android.os.Handler.handleCallback(Handler.java:751) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6776) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)
It was working before but it seem the problem is since I use Android 7 (API 24).
This is my code :
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
imageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "fname_" +
String.valueOf(System.currentTimeMillis()) + ".jpg"));
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
回答1:
If your targetSdkVersion is 24 or higher, we have to use FileProvider class to give access to the particular file or folder to make them accessible for other apps. We create our own class inheriting FileProvider in order to make sure our FileProvider doesn't conflict with FileProviders declared in imported dependencies as described here.
Find relevant discussion here
Since Android 7, we don't use file: scheme as uri for intent, you have to use FileProvider.
回答2:
Well, the correct way of doing it is by using FileProvider
(as mentioned in developer). But I have figured out a naughty way to do it without adding FileProvider
. It is obviously a workaround but it works.
In your Activity, add the following lines:
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
This will simply ignore the URI exposure and you will get the access.
Yes, I know that this is not the best practice. But I just wanted to provide an alternative to it.
Still, recommended way is by using FileProvider
.
来源:https://stackoverflow.com/questions/44821017/fileuriexposedexception-using-android-7