如何从内置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

其他回答

Kotlin开发人员可以使用

var webpage = Uri.parse(url)
    if (!url.startsWith("http://") && !url.startsWith("https://")) {
        webpage = Uri.parse("http://$url")
    }
    val intent = Intent(Intent.ACTION_VIEW, webpage)
    if (intent.resolveActivity(packageManager) != null) {
        startActivity(intent)
    }

短代码版本。。。

 if (!strUrl.startsWith("http://") && !strUrl.startsWith("https://")){
     strUrl= "http://" + strUrl;
 }


 startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(strUrl)));

只需使用简短的一个,即可在浏览器中打开您的Url:

Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("YourUrlHere"));
startActivity(browserIntent);

试试看:

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);
dataWebView.setWebViewClient(new VbLinksWebClient() {
     @Override
     public void onPageFinished(WebView webView, String url) {
           super.onPageFinished(webView, url);
     }
});




public class VbLinksWebClient extends WebViewClient
{
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url)
    {
        view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url.trim())));
        return true;
    }
}