14

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 ?

Ajay Chauhan
  • 1,471
  • 4
  • 17
  • 37

3 Answers3

26

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().

David Wasser
  • 93,459
  • 16
  • 209
  • 274
5

From Docs

Retrieve all activities that can be performed for the given intent.

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.

AskNilesh
  • 67,701
  • 16
  • 123
  • 163
2

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.

waqaslam
  • 67,549
  • 16
  • 165
  • 178
  • if this can we used to show a chooser then what does Intent.createChooser(intent, title); do ? – Ajay Chauhan Oct 10 '18 at 12:00
  • @AjayChauhan When you directly use `createChooser()` you can control some of the behaviour (ie: setting the "title" for the chooser). When Android creates the chooser itself (because it needs the user to pick something to complete `resolveActivity()`), it uses the default chooser. – David Wasser Oct 10 '18 at 12:36