Created
November 9, 2018 16:26
-
-
Save minas1/f920c037e511f71a1d06c9261f3307be to your computer and use it in GitHub Desktop.
Exclude your own Activity from Activity.startActivity(Intent) chooser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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