我想以编程方式查找默认浏览器的包名称。
(知道包装名称,我可以,例如,将其图标放在按钮上,或在没有启动器的情况下启动。)
resolveActivity()
中有PackageManager
,但Google文档说:如果找到多个匹配活动并且没有默认设置,则返回包含其他内容的ResolveInfo,例如活动解析器。
答案 0 :(得分:3)
我希望有人可以写一些更优雅的东西。但这些东西有效:
public static ComponentName getDefaultBrowserComponent(Context context) {
Intent i = new Intent()
.setAction(Intent.ACTION_VIEW)
.setData(new Uri.Builder()
.scheme("http")
.authority("x.y.z")
.appendQueryParameter("q", "x")
.build()
);
PackageManager pm = context.getPackageManager();
ResolveInfo default_ri = pm.resolveActivity(i, 0); // may be a chooser
ResolveInfo browser_ri = null;
List<ResolveInfo> rList = pm.queryIntentActivities(i, 0);
for (ResolveInfo ri : rList) {
if (ri.activityInfo.packageName.equals(default_ri.activityInfo.packageName)
&& ri.activityInfo.name.equals(default_ri.activityInfo.name)
) {
return ri2cn(default_ri);
} else if ("com.android.browser".equals(ri.activityInfo.packageName)) {
browser_ri = ri;
}
}
if (browser_ri != null) {
return ri2cn(browser_ri);
} else if (rList.size() > 0) {
return ri2cn(rList.get(0));
} else if (default_ri == null) {
return null;
} else {
return ri2cn(default_ri);
}
}
private static ComponentName ri2cn(ResolveInfo ri) {
return new ComponentName(ri.activityInfo.packageName, ri.activityInfo.name);
}