I want to open the phone's gallery using a button from my application. I'm using something like this:
goToGalleryButton.setOnClickListener {
val intent = Intent()
intent.action = Intent.ACTION_VIEW
intent.type = "image/*"
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
startActivity(intent)
}
After pressing the button, a pop-up for choosing the desired application appears. If I choose the Google Photos application everything is good and I can see all the images and videos as I want, but if I choose the Samsung's gallery I get a toast with "Unsupported file" error message.
Something similar happens on Huawei devices on choosing the native gallery application.
Is there a way to avoid that error message when opening the native gallery app?
if I choose the Samsung's gallery I get a toast with "Unsupported file" error message
Sure. Your Intent
is broken:
ACTION_VIEW
takes a Uri
of the content to be viewed — you are not including thatACTION_VIEW
takes a concrete MIME type of that content — you are using a wildcardYou are assuming that the developers of apps capable of viewing images will "gracefully degrade" when they receive a flawed Intent
. That happens to be the case for Google Photos, apparently. It will not be the case in general.
I want to open the phone's gallery using a button from my application
I am interpreting this as meaning that you want to do the same thing as would happen if the user tapped the launcher icon for that app. If so:
Intent
for ACTION_MAIN
and CATEGORY_LAUNCHER
Intent
to that one, where the selector will help constrain which apps are used for the chooserProbably CATEGORY_APP_GALLERY
will be the right category to use for the selector Intent
.
You can combine all of that using makeMainSelectorActivity()
:
val intent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN, Intent.CATEGORY_APP_GALLERY)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)