Reputation: 816
this is not a duplicate. I checked carefully before posting this one.
There's a similar question here for reference but it is about OPEN_DOCUMENT_TREE. Mine's about ACTION_OPEN_DOCUMENT
The task to accomplish is to let the user pick a single image/jpeg from their device's photo gallery. Here is my code:
ActivityResultLauncher<String[]> galleryActivityLauncher = registerForActivityResult(new ActivityResultContracts.OpenDocument(), picked -> {
if (picked != null) {
processPickedImage(picked);
}
});
try {
galleryActivityLauncher.launch(new String[]{"image/jpeg"});
} catch (ActivityNotFoundException e) {
//Fallback to old legacy way.
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/jpeg");
startActivityForResult(intent, REQUEST_CODE_GALLERY);
}
Even with the current try/catch, the legacy fallback is still crashing again with the same exception as the logcat shows:
Fatal Exception: android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.OPEN_DOCUMENT cat=[android.intent.category.OPENABLE] typ=image/jpeg }
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:2220)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1859)
at android.app.Activity.startActivityForResult(Activity.java:5623)
at androidx.activity.ComponentActivity.startActivityForResult(ComponentActivity.java:754)
at android.app.Activity.startActivityForResult(Activity.java:5576)
at androidx.activity.ComponentActivity.startActivityForResult(ComponentActivity.java:735)
Any ideas why is this happening in such a modern device with Android 13? What is the alternative here? Maybe ACTION_GET_CONTENT or should I inform the user that their device is incompatible?
Alternative solution...
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, REQUEST_CODE_LOAD_IMAGE);
Reference post: What is the real difference between ACTION_OPEN_DOCUMENT and ACTION_GET_CONTENT
Upvotes: 0
Views: 423
Reputation: 1007474
I am uncertain what galleryActivityLauncher
is. This comment suggests that it is ActivityResultContracts.OpenDocument
. If so, then the implementation of ActivityResultContracts.OpenDocument
uses ACTION_OPEN_DOCUMENT
, so if one fails, the other typically will as well.
ACTION_GET_CONTENT
(or ActivityResultContracts.GetContent
) is another possible fallback, as you suggest in your question.
As to why this is not supported, if that device does not ship with the Play Store and other Google services, it is not required to adhere to compatibility guidelines.
Upvotes: 0