我试图获得给定Intent的默认/首选应用程序.例如,当用户安装第二个Web浏览器时,尝试打开一个URL,他或她将获得如下对话框:
如果用户然后选择该操作选项的“默认使用”选项,则当按下URL时,该对话框将不再打开.
我正在处理一个应该知道这个默认或首选应用/操作的应用程序.我该怎么做?我目前正在使用下面的代码,但getPreferredPackage不返回任何内容:
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(); } } }
我究竟做错了什么?这甚至是正确的做法吗?
解决方法
那么这个解决方案比我做的简单得多(尽管这很简单).以下代码是我的解决方案:
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();