I get android.os.StrictMode.onFileUriExposed
exception when trying to send a file with a Intent. It's my understanding that this is because I'm targeting 24> and file://
is not supported anymore, content://
should be used.
First I would like to say that I have seen similar questions like this, this and i'v also seen this blog post.
But the problem is, all of the post refer to URI when taking a picture, in my case the file is saved successfully using Uri and now I want to send the image using Intent like below:
shareBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
Uri screenshotUri = Uri.parse("file://" + directoryToStore + "/" + filename);
//the Uri above - file:///storage/emulated/0/Android/data/myPackageName/files/SavedImages/test.jpeg
sharingIntent.setType("image/jpeg");
sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
startActivity(Intent.createChooser(sharingIntent, "Share image using"));
}
});
By doing the above I only get a crash on some devices running 19>. Testing on my Samsung J7Pro (Android 7.0 API 24) I don't get a crash.
I have seen that some of that answers say that I can use:
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
But it's not the preferred way.
So, my question is. How should I handle sending files when targeting 24>. Should I do a if/else statement checking the version like if (Build.VERSION.SDK_INT >= 19) {
and then use normal Uri for devices running <24 and how should I change file://
to content://
? I also don't understand why the crash only happens on some devices.
EDIT 1:
I have done what the answer below suggested but the file is not passed with the intent, instead I get a Toast
saying Unable to attach file
when I try to email the image.