Skip to content

Instantly share code, notes, and snippets.

@minas1
Created November 9, 2018 16:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save minas1/f920c037e511f71a1d06c9261f3307be to your computer and use it in GitHub Desktop.
Save minas1/f920c037e511f71a1d06c9261f3307be to your computer and use it in GitHub Desktop.
Exclude your own Activity from Activity.startActivity(Intent) chooser
/**
* Attempts to start an activity to handle the given intent, excluding activities of this app.
* <ul>
* <li>If the user has set a default activity (which does not belong in this app's package), it is opened without prompt.</li>
* <li>Otherwise, an intent chooser is displayed that excludes activities of this app's package.</li>
* </ul>
*
* @param context context
* @param intent intent to open
* @param chooserTitle the title that will be displayed for the intent chooser in case one needs to be displayed.
*/
static void startActivityExcludingOwnApp(@NonNull Context context, @NonNull Intent intent, @NonNull String chooserTitle) {
PackageManager packageManager = context.getPackageManager();
List<Intent> possibleIntents = new ArrayList<>();
Set<String> possiblePackageNames = new HashSet<>();
for (ResolveInfo resolveInfo : packageManager.queryIntentActivities(intent, 0)) {
String packageName = resolveInfo.activityInfo.packageName;
if (!packageName.equals(context.getPackageName())) {
Intent possibleIntent = new Intent(intent);
possibleIntent.setPackage(resolveInfo.activityInfo.packageName);
possiblePackageNames.add(resolveInfo.activityInfo.packageName);
possibleIntents.add(possibleIntent);
}
}
@Nullable ResolveInfo defaultResolveInfo = packageManager.resolveActivity(intent, 0);
if (defaultResolveInfo == null || possiblePackageNames.isEmpty()) {
throw new ActivityNotFoundException();
}
// If there is a default app to handle the intent (which is not this app), use it.
if (possiblePackageNames.contains(defaultResolveInfo.activityInfo.packageName)) {
context.startActivity(intent);
}
else { // Otherwise, let the user choose.
Intent intentChooser = Intent.createChooser(possibleIntents.remove(0), chooserTitle);
intentChooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, possibleIntents.toArray(new Parcelable[]{}));
context.startActivity(intentChooser);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment