获取preferred /默认的应用程序在Android应用程序、preferred、Android

2023-09-12 22:51:52 作者:柚茶

我想获得一个给定的意图默认/ preferred应用。例如,当用户安装第二个网络浏览器,然后尝试打开一个URL时,他或她将得到一个像这样的对话:

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:

如果用户随后选择的使用默认情况下,这个动作的选项,然后在对话框不再打开时,一个网址为pressed。

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.

我的工作是应该知道这是什么的默认或 preferred 的应用程序/动作是一个应用程序。我该怎么做呢?我目前使用code以下,但获取preferredPackage 不返回任何内容:

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?

推荐答案

好了,解决的办法竟然是简单得多的比我做了(尽管这是记录非常糟糕)。下面code是我的解决方案:

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();