Get Preferred/Default app on Android

Phil picture Phil · Dec 24, 2011 · Viewed 11.7k times · Source

I am trying to get the default/preferred application for a given Intent. For example, when the user installs a second web browser, then attempts to open a URL, he or she will get a dialog like this:

default browser selector

If the user then selects the Use by default for this action option, then the dialog box no longer opens when a URL is pressed.

I am working on an application that should be aware of what this default or preferred app/action is. How do I do this? I am currently using the code below, but getPreferredPackage doesn't return anything:

Intent i = (new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com"));
PackageManager pm = context.getPackageManager();
final List<ResolveInfo> list = pm.queryIntentActivities(i, 0);
IntentFilter ifilter = new IntentFilter(i.getAction());
if (i.getCategories() != null) {
    for(String category : i.getCategories()) {
        ifilter.addCategory(category);
    }
}
List<IntentFilter> filters = new ArrayList<IntentFilter>();
filters.add(ifilter);
List<ComponentName> preferredActivities = new ArrayList<ComponentName>();
pm.getPreferredActivities(filters, preferredActivities, null);
for (ComponentName activity : preferredActivities) {
    for (ResolveInfo rinfo : list) {
        if (rinfo.activityInfo.applicationInfo.packageName.equals(activity.getPackageName())) {
            try {
                final PackageInfo pi = pm.getPackageInfo(activity.getPackageName(), 0);
                Toast.makeText(context, pm.getApplicationLabel(pi.applicationInfo), Toast.LENGTH_SHORT).show();
            }
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
    }
}

What am I doing wrong? Is this even the right approach?

Answer

Phil picture Phil · Dec 24, 2011

Well, the solution turned out to be much simpler than I made it (although this is very poorly documented). The following code is my solution:

Intent i = (new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com"));
PackageManager pm = context.getPackageManager();
final ResolveInfo mInfo = pm.resolveActivity(i, 0);
Toast.makeText(context, pm.getApplicationLabel(mInfo.activityInfo.applicationInfo), Toast.LENGTH_LONG).show();