DEV Community

daisy1754
daisy1754

Posted on

Removing self from Android implicit intent

Android provides an implicit intent to open apps based on user's intent (eg., I want to take a picture). It is simple yet very useful feature for users.

It may however be tricky when app can handle multiple implicit intent. For instance, if you develop a photo sharing app, your app can be a both receiver and sender of 'export an image' intent at the same time. When your users try to export an image from your app, it'd be awkward if your app is also in the receiver list.

To avoid situation like this, you can queryIntentActivities and explicitly filter intent as follows:

public static Intent createChooser(Context context, Intent target, CharSequence title) {
  List<ResolveInfo> resolveInfoList = context.getPackageManager().queryIntentActivities(
      target, PackageManager.MATCH_DEFAULT_ONLY);
  if (resolveInfoList.isEmpty()) {
    return Intent.createChooser(target, title);
  }

  Collections.sort(
      resolveInfoList, 
      new ResolveInfo.DisplayNameComparator(context.getPackageManager()));
  List<Intent> targetIntents = new ArrayList<Intent>();
  for (ResolveInfo resolveInfo : resolveInfoList) {
    if (context.getApplicationContext().getPackageName().equals(
        resolveInfo.activityInfo.packageName)) {
      continue;
    }
    Intent intent = new Intent(target);
    intent.setPackage(resolveInfo.activityInfo.packageName);
    intent.setClassName(
        resolveInfo.activityInfo.packageName, resolveInfo.activityInfo.name);
    targetIntents.add(intent);
  }

  Intent chooserIntent = Intent.createChooser(targetIntents.remove(0), title);
  chooserIntent.putExtra(
      Intent.EXTRA_INITIAL_INTENTS, 
      targetIntents.toArray(new Parcelable[]{}));
  return chooserIntent;
  }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
chrisvasqm profile image
Christian Vasquez • Edited

Hey daisy1754,

Thanks for sharing this!

Side note:

If you add the word "java" right after the triple backtick on the code block it will make your code easier to read.

Examples

Without "java"

public void main(String[] args) {
    System.out.println("Hello World!");
}

With "java"

public void main(String[] args) {
    System.out.println("Hello World!");
}