如何从内置web浏览器而不是应用程序中的代码打开URL?
我试过了:
try {
Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(download_link));
startActivity(myIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "No application can handle this request."
+ " Please install a webbrowser", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
但我有个例外:
No activity found to handle Intent{action=android.intent.action.VIEW data =www.google.com
Chrome自定义选项卡现在可用:
第一步是将自定义选项卡支持库添加到build.gradle文件中:
dependencies {
...
compile 'com.android.support:customtabs:24.2.0'
}
然后,要打开chrome自定义选项卡:
String url = "https://www.google.pt/";
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.launchUrl(this, Uri.parse(url));
有关详细信息:https://developer.chrome.com/multidevice/android/customtabs
所以我找了很长时间,因为所有其他答案都是打开该链接的默认应用程序,而不是默认浏览器,这就是我想要的。
我终于做到了:
// gathering the default browser
final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://"));
final ResolveInfo resolveInfo = context.getPackageManager()
.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
String defaultBrowserPackageName = resolveInfo.activityInfo.packageName;
final Intent intent2 = new Intent(Intent.ACTION_VIEW);
intent2.setData(Uri.parse(url));
if (!defaultBrowserPackageName.equals("android")) {
// android = no default browser is set
// (android < 6 or fresh browser install or simply no default set)
// if it's the case (not in this block), it will just use normal way.
intent2.setPackage(defaultBrowserPackageName);
}
context.startActivity(intent2);
顺便说一句,你可以注意到context.whatever,因为我已经将它用于静态util方法,如果你在一个活动中这样做,它是不需要的。
android.webkit.URLUtil自Api级别1(android 1.0)以来,guessUrl(String)方法工作得非常好(即使使用file://或data://)。用作:
String url = URLUtil.guessUrl(link);
// url.com -> http://url.com/ (adds http://)
// http://url -> http://url.com/ (adds .com)
// https://url -> https://url.com/ (adds .com)
// url -> http://www.url.com/ (adds http://www. and .com)
// http://www.url.com -> http://www.url.com/
// https://url.com -> https://url.com/
// file://dir/to/file -> file://dir/to/file
// data://dataline -> data://dataline
// content://test -> content://test
在“活动”调用中:
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(URLUtil.guessUrl(download_link)));
if (intent.resolveActivity(getPackageManager()) != null)
startActivity(intent);
有关详细信息,请查看完整的guessUrl代码。