As I can see in Android documentation when trying to build implicit intents when sending the user to another app. These are the two approaches to avoid ActivityNotFoundException.
First one :
Intent mapIntent = new Intent(Intent.ACTION_VIEW, location);
PackageManager packageManager = getPackageManager();
List<ResolveInfo> activities = packageManager.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
boolean isIntentSafe = activities.size() > 0;
Second one :
Intent chooser = Intent.createChooser(intent, title);
if (intent.resolveActivity(getPackageManager()) != null) {
}
Now my doubt is whats the differnece and which one should i use ?
Depends what you want to do.
If you just want to prevent 'ActivityNotFoundException', either method will work. Neither is "best". They do basically the same thing. You want to know if there is at least 1 Activity
that can handle your Intent
.
Otherwise:
queryIntentActivities()
returns a list of all activities that can handle the Intent
. resolveActivity()
returns the "best" Activity
that can handle the Intent
Therefore, if you want to know all the activities that can handle your Intent
, you would use queryIntentActivities()
and if you want to know what Android thinks is the "best" Activity
, then you would use resolveActivity()
.
From Docs
queryIntentActivities
Retrieve all activities that can be performed for the given intent.
resolveActivity
Determine the best action to perform for a given Intent.
This is how Intent.resolveActivity(PackageManager)
finds an activity if a class has not been explicitly specified.
Note: if using an implicit Intent (without an explicit ComponentName specified), be sure to consider whether to set the MATCH_DEFAULT_ONLY
only flag. You need to do so to resolve the activity in the same way that Context.startActivity(Intent)
and Intent.resolveActivity(PackageManager)
do.
In short, queryIntentActivities
returns a List
of all available ResolveInfo
that can handle your given Intent
and in contrast resolveActivity
returns the single best suited ResolveInfo
.
Hence, one can be used to show a chooser and the other can be used to launch the app directly.
For more info, read their official documents.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With