最近碰到一个同事询问如何查询本地安装的浏览器列表,其使用的代码如下:
public static List<ResolveInfo> getBrowserList(Context context) { PackageManager packageManager = context.getPackageManager(); Intent intent = new Intent(Intent.ACTION_VIEW); intent.addCategory(Intent.CATEGORY_BROWSABLE); intent.setData(Uri.parse("http://www.baidu.com/")); List<ResolveInfo> activities = packageManager.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY); return activities; }
运行结果如下:
com.android.browser
com.tencent.mtt
com.android.chrome
com.taobao.taobao
结果不知道怎么淘宝客户端就被当作browser添加进来了,后来发现原来淘宝客户端也添加了Intent.CATEGORY_BROWSABLE这个category过滤,但是使用
Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.addCategory(Intent.CATEGORY_DEFAULT); intent.setData(Uri.parse("http://www.baidu.com/"));
ComponentName name = new ComponentName("android",
"com.android.internal.app.ResolverActivity");
intent.setComponent(name);
context.startActivity(intent);
这样调起系统选择的浏览器的界面就没有出现淘宝客户端,这让我感觉很意外,于是看了com.android.internal.app.ResolverActivity的代码,发现有这样一段代码:
// Only display the first matches that are either of equal // priority or have asked to be default options. ResolveInfo r0 = currentResolveList.get(0); for (int i=1; i<N; i++) { ResolveInfo ri = currentResolveList.get(i); if (r0.priority != ri.priority || r0.isDefault != ri.isDefault) { while (i < N) { if (mOrigResolveList == currentResolveList) { mOrigResolveList = new ArrayList<ResolveInfo>(mOrigResolveList); } currentResolveList.remove(i); N--; } } }
于是将获取浏览器列表的逻辑改成了如下:
public static List<ResolveInfo> getBrowserList(Context context) { PackageManager packageManager = context.getPackageManager(); Intent intent = new Intent(Intent.ACTION_VIEW); intent.addCategory(Intent.CATEGORY_BROWSABLE); intent.setData(Uri.parse("http://www.baidu.com/")); List<ResolveInfo> activities = packageManager.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY); ResolveInfo r0 = activities.get(0); Iterator<ResolveInfo> activity_iter = activities.iterator(); while (activity_iter.hasNext()) { ResolveInfo resolveInfo = activity_iter.next(); if (r0.priority != resolveInfo.priority ||
r0.isDefault != resolveInfo.isDefault) { activities.remove(resolveInfo); } } return activities; }
运行得到的结果如下:
com.android.browser
com.tencent.mtt
com.android.chrome
总结:第一个是获取到的是最匹配查询条件的系统软件,所有app的优先级与其相同的即为所要获取的列表项。