继@philippe _ b 的回答之后,我想补充一下,如果没有安装 Chrome,这段代码将无法工作。还有一种情况下,它不会工作-这是这种情况下,Chrome 不选择作为默认浏览器(但安装)或即使没有浏览器选择作为默认。
在这种情况下,还可以在代码中添加以下 catch 部分。
try {
Intent i = new Intent("android.intent.action.MAIN");
i.setComponent(ComponentName.unflattenFromString("com.android.chrome/com.android.chrome.Main"));
i.addCategory("android.intent.category.LAUNCHER");
i.setData(Uri.parse("http://mysuperwebsite"));
startActivity(i);
}
catch(ActivityNotFoundException e) {
// Chrome is probably not installed
// OR not selected as default browser OR if no Browser is selected as default browser
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("somesite.com"));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
public static final String GOOGLECHROME_NAVIGATE_PREFIX = "googlechrome://navigate?url=";
下一个用法:
Intent intent = new Intent("android.intent.action.VIEW", Uri.parse("googlechrome://navigate?url=chrome-native://newtab/"));
因此,解决方案是(注意,不应对 URL 进行编码)
void openUrlInChrome(String url) {
try {
try {
Uri uri = Uri.parse("googlechrome://navigate?url="+ url);
Intent i = new Intent(Intent.ACTION_VIEW, uri);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
} catch (ActivityNotFoundException e) {
Uri uri = Uri.parse(url);
// Chrome is probably not installed
// OR not selected as default browser OR if no Browser is selected as default browser
Intent i = new Intent(Intent.ACTION_VIEW, uri);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
} catch (Exception ex) {
Timber.e(ex, null);
}
}
public void openUrlInBrowser(Context context, String url) {
// Find out package name of default browser
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://"));
ResolveInfo resolveInfo = context.getPackageManager().resolveActivity(browserIntent, PackageManager.MATCH_DEFAULT_ONLY);
String packageName = resolveInfo.activityInfo.packageName;
// Use the explicit browser package name
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
i.setPackage(packageName);
context.startActivity(i);
}