How to use PackageManager to retrieve dialer/brows

2019-06-13 17:03发布

问题:

I am writing a launcher and I need to find the dialer, browser, sms and camera app to put as shortcuts on the dock.

I assume different vendors like Samsung/HTC/Google will all have different apps for each of these with different package names.

Is there a way to use the PackageManager to get the default dialer app for example?

EDIT:

As per the advice given below I ended up implementing it like this:

Intent i = new Intent(Intent.ACTION_CALL);
i.setData(Uri.parse("tel:123456789"));
ResolveInfo resolveInfo = pm.resolveActivity(i, 0);
AppModel result = null;
if (resolveInfo != null) {
    ActivityInfo activityInfo = resolveInfo.activityInfo;
    if (activityInfo != null) {
        if ("android".equals(activityInfo.packageName)) {
            // no default activity.. choose first
            List<ResolveInfo> resolveInfos = m.queryIntentActivities(i, 0);
            for (ResolveInfo rInfo : resolveInfos) {
                result = new AppModel(context, rInfo.activityInfo.applicationInfo);
                break;
            }

        } else {
            ApplicationInfo appInfo = activityInfo.applicationInfo;
            if (appInfo != null) {
                result = new AppModel(context, appInfo);
            }
        }

    }

}

回答1:

Create an Intent identifying what you want to do (e.g., an ACTION_DIAL Intent with a fake phone number), then use PackageManager and either resolveActivity() or queryIntentActivities().

However, bear in mind that there may not be a default for those operations, for any number of reasons, including:

  • The device is not a phone

  • The user does not have rights to any matching app, courtesy of restricted profiles on Android 4.3+ devices

  • The user may have installed 2+ apps for that Intent, and has not yet chosen a default (resolveActivity() will return the system chooser)

Also, the answer of what the default app is will change over time, just as you are hoping that the user's chosen home screen default app will change to be yours.