I'm trying this code to open the gallery. My app makes a directory in the gallery. I can see my directory in the gallery. I'm trying to open it from my app by this code:-
File sdDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File f = new File(sdDir, "Photo Location Note");
Intent i = new Intent();
i.setAction(Intent.ACTION_VIEW);
i.setDataAndType(Uri.withAppendedPath(Uri.fromFile(f), "Photo Location Note"), "image/*");
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
It opens the gallery and shows a toast message as "Unable to find item". It doesn't open my directory "Photo Location Note" in the gallery.
How can I open my directory "Photo Location Note" in the gallery?
It works for me on Android 11 and earlier versions:
public void openPhoto(Context context, String directory){
File file = new File(directory);
if(!file.exists()){
return;
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N ?
FileProvider.getUriForFile(context,context.getPackageName() + ".provider", file) : Uri.fromFile(file),"image/*");
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent = Intent.createChooser(intent, "Open File");
context.startActivity(intent);
}
This fragment is important:
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);