如何从内置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
Kotlin溶液
所有答案都是在该url的默认应用程序中打开该url。我想总是在浏览器中打开任何url。我需要一些kotlin的解决方案,并实现了下面的代码。
fun getPackageNameForUrl(context: Context, url: String): String? {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
val resolveInfo = context.packageManager.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY)
return resolveInfo?.activityInfo?.packageName
}
fun openInBrowser(context: Context, url: String) {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
val packageName = getPackageNameForUrl(context, "http://")
packageName?.takeIf {
it == "android"
}?.let { intent.setPackage(defaultBrowserPackageName); }
startActivity(context, intent, null)
}
试试看:
Uri uri = Uri.parse("https://www.google.com");
startActivity(new Intent(Intent.ACTION_VIEW, uri));
或者如果您希望在活动中打开web浏览器,请执行以下操作:
WebView webView = (WebView) findViewById(R.id.webView1);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
webView.loadUrl(URL);
如果您想在浏览器中使用缩放控制,则可以使用:
settings.setSupportZoom(true);
settings.setBuiltInZoomControls(true);
//OnClick侦听器
@Override
public void onClick(View v) {
String webUrl = news.getNewsURL();
if(webUrl!="")
Utils.intentWebURL(mContext, webUrl);
}
//你的Util方法
public static void intentWebURL(Context context, String url) {
if (!url.startsWith("http://") && !url.startsWith("https://")) {
url = "http://" + url;
}
boolean flag = isURL(url);
if (flag) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse(url));
context.startActivity(browserIntent);
}
}