2
votes

In my app, I show a list of posts where posts may have image. When user clicks on the post image, the create chooser shows available options like “photo”, “gallery”. My question is,why can't gallery open the image on android 7.0 or API 24 and above? I get an error “can not open file.” On API level 23 and below, I provide actual file path which seems to be working fine. I confirmed following things before posting this question.Interesting part is "Photo" could open it.

  1. I get the proper content uri using FileProvider. My uri looks like this:

    content://package.fileprovider/attachment/filename

  2. I am using the proper mime type.

  3. I am using proper intent and permission flags.Please see the below code:

Intent myIntent = new Intent(Intent.ACTION_VIEW); myIntent.putExtra(ShareCompat.EXTRA_CALLING_PACKAGE, getActivity().getPackageName()); myIntent.putExtra(ShareCompat.EXTRA_CALLING_ACTIVITY, getActivity().getComponentName());

myIntent.setDataAndType(uri, mimeType); myIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); startActivity(Intent.createChooser(myIntent, "Open file:"));

3
Check LogCat to see if your gallery app logged anything of note when it displayed that message. It may be that your device has a buggy gallery app.CommonsWare
Thanks for reply. I checked the LogCat. I didn't see any note or message. Any other suggestions?Amruta
All works on Nougat. No problems. Two different devices.greenapps
I am using LG G5, android 7.0. It's not working. Do you see any problem with code?Amruta

3 Answers

2
votes

Only for Android API 24 above - Nougat device

 File file = new File(String.valueOf(path), imageName+".png"); //it is image file name.
 if(Build.VERSION.SDK_INT>=24){ 
      Intent intent = new Intent();

      intent.setAction(Intent.ACTION_VIEW);

      intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //must provide

      Uri photoUri = FileProvider.getUriForFile(YourCurrentActivity.this, 
                      android.support.v4.BuildConfig.APPLICATION_ID + 
                      ".fileprovider", finalFile);

      intent.setData(photoUri);

      YourCurrentActivity.this.startActivity(intent);
 }
0
votes

You can open file URI by adding this to your Application:

if(Build.VERSION.SDK_INT>=24){
    try{
        Method m = StrictMode.class.getMethod("disableDeathOnFileUriExposure");
        m.invoke(null);
    }catch(Exception e){
        e.printStackTrace();
    }
}

Content may be the new thing, but in my opinion there aren't enough 7.0 devices active compared to lower API devices to justify the non-use of this deprecated method. 7.0 devices can still use this too, quiet well.

0
votes

Maybe on Nougat you need to take permission from a user to read and write. Your code will work below N. So ask user to grant read permission and also check for FileProvider you will need that too.