如何从我的应用程序在 Android 的 Web 浏览器中打开 URL?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2201917/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 04:56:17  来源:igfitidea点击:

How can I open a URL in Android's web browser from my application?

androidurlandroid-intentandroid-browser

提问by Arutha

How to open an URL from code in the built-in web browser rather than within my application?

如何从内置 Web 浏览器中的代码而不是我的应用程序中打开 URL?

I tried this:

我试过这个:

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();
}

but I got an Exception:

但我有一个例外:

No activity found to handle Intent{action=android.intent.action.VIEW data =www.google.com

回答by Mark B

Try this:

尝试这个:

Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(browserIntent);

That works fine for me.

这对我来说很好用。

As for the missing "http://" I'd just do something like this:

至于缺少的“http://”,我只会做这样的事情:

if (!url.startsWith("http://") && !url.startsWith("https://"))
   url = "http://" + url;

I would also probably pre-populate your EditText that the user is typing a URL in with "http://".

我也可能会预先填充用户正在使用“http://”键入 URL 的 EditText。

回答by Jorgesys

a common way to achieve this is with the next code:

实现此目的的常用方法是使用下一个代码:

String url = "http://www.stackoverflow.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url)); 
startActivity(i); 

that could be changed to a short code version ...

可以更改为短代码版本......

Intent intent = new Intent(Intent.ACTION_VIEW).setData(Uri.parse("http://www.stackoverflow.com"));      
startActivity(intent); 

or :

或者 :

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.stackoverflow.com")); 
startActivity(intent);

the shortest! :

最短的!:

startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.stackoverflow.com")));

happy coding!

快乐编码!

回答by kenju

Simple Answer

简单的答案

You can see the official sample from Android Developer.

您可以查看来自 Android Developer 的官方示例

/**
 * Open a web page of a specified URL
 *
 * @param url URL to open
 */
public void openWebPage(String url) {
    Uri webpage = Uri.parse(url);
    Intent intent = new Intent(Intent.ACTION_VIEW, webpage);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}

How it works

这个怎么运作

Please have a look at the constructor of Intent:

请看一下 的构造函数Intent

public Intent (String action, Uri uri)

You can pass android.net.Uriinstance to the 2nd parameter, and a new Intent is created based on the given data url.

您可以将android.net.Uri实例传递给第二个参数,并根据给定的数据 url 创建一个新的 Intent。

And then, simply call startActivity(Intent intent)to start a new Activity, which is bundled with the Intent with the given URL.

然后,只需调用startActivity(Intent intent)即可启动一个新的 Activity,该 Activity 与具有给定 URL 的 Intent 捆绑在一起。

Do I need the ifcheck statement?

我需要if支票声明吗?

Yes. The docssays:

是的。该文件说:

If there are no apps on the device that can receive the implicit intent, your app will crash when it calls startActivity(). To first verify that an app exists to receive the intent, call resolveActivity() on your Intent object. If the result is non-null, there is at least one app that can handle the intent and it's safe to call startActivity(). If the result is null, you should not use the intent and, if possible, you should disable the feature that invokes the intent.

如果设备上没有可以接收隐式意图的应用程序,您的应用程序将在调用 startActivity() 时崩溃。要首先验证应用程序是否存在以接收 Intent,请在您的 Intent 对象上调用 resolveActivity()。如果结果不为空,则至少有一个应用程序可以处理该意图,并且调用 startActivity() 是安全的。如果结果为空,则不应使用该意图,如果可能,应禁用调用该意图的功能。

Bonus

奖金

You can write in one line when creating the Intent instance like below:

您可以在创建 Intent 实例时写在一行中,如下所示:

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));

回答by MikeNereson

In 2.3, I had better luck with

在 2.3 中,我有更好的运气

final Intent intent = new Intent(Intent.ACTION_VIEW).setData(Uri.parse(url));
activity.startActivity(intent);

The difference being the use of Intent.ACTION_VIEWrather than the String "android.intent.action.VIEW"

区别在于使用Intent.ACTION_VIEW而不是字符串"android.intent.action.VIEW"

回答by nikki

Try this:

尝试这个:

Uri uri = Uri.parse("https://www.google.com");
startActivity(new Intent(Intent.ACTION_VIEW, uri));

or if you want then web browser open in your activity then do like this:

或者,如果您想在您的活动中打开网络浏览器,请执行以下操作:

WebView webView = (WebView) findViewById(R.id.webView1);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
webView.loadUrl(URL);

and if you want to use zoom control in your browser then you can use:

如果您想在浏览器中使用缩放控件,则可以使用:

settings.setSupportZoom(true);
settings.setBuiltInZoomControls(true);

回答by Dmytro Danylyk

If you want to show user a dialogue with all browser list, so he can choose preferred, here is sample code:

如果您想向用户显示所有浏览器列表的对话,以便他可以选择首选,这里是示例代码:

private static final String HTTPS = "https://";
private static final String HTTP = "http://";

public static void openBrowser(final Context context, String url) {

     if (!url.startsWith(HTTP) && !url.startsWith(HTTPS)) {
            url = HTTP + url;
     }

     Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
     context.startActivity(Intent.createChooser(intent, "Choose browser"));// Choose browser is arbitrary :)

}

回答by android developer

Just like the solutions other have written (that work fine), I would like to answer the same thing, but with a tip that I think most would prefer to use.

就像其他人写的解决方案(工作正常)一样,我想回答同样的问题,但我认为大多数人更愿意使用一个技巧。

In case you wish the app you start to open in a new task, indepandant of your own, instead of staying on the same stack, you can use this code:

如果您希望应用程序开始在一个新任务中打开,独立于您自己的任务,而不是停留在同一个堆栈上,您可以使用以下代码:

final Intent intent=new Intent(Intent.ACTION_VIEW,Uri.parse(url));
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY|Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET|Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
startActivity(intent);

There is also a way to open the URL in Chrome Custom Tabs. Example in Kotlin :

还有一种方法可以在Chrome Custom Tabs 中打开 URL 。Kotlin 中的示例:

@JvmStatic
fun openWebsite(activity: Activity, websiteUrl: String, useWebBrowserAppAsFallbackIfPossible: Boolean) {
    var websiteUrl = websiteUrl
    if (TextUtils.isEmpty(websiteUrl))
        return
    if (websiteUrl.startsWith("www"))
        websiteUrl = "http://$websiteUrl"
    else if (!websiteUrl.startsWith("http"))
        websiteUrl = "http://www.$websiteUrl"
    val finalWebsiteUrl = websiteUrl
    //https://github.com/GoogleChrome/custom-tabs-client
    val webviewFallback = object : CustomTabActivityHelper.CustomTabFallback {
        override fun openUri(activity: Activity, uri: Uri?) {
            var intent: Intent
            if (useWebBrowserAppAsFallbackIfPossible) {
                intent = Intent(Intent.ACTION_VIEW, Uri.parse(finalWebsiteUrl))
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_NO_HISTORY
                        or Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET or Intent.FLAG_ACTIVITY_MULTIPLE_TASK)
                if (!CollectionUtil.isEmpty(activity.packageManager.queryIntentActivities(intent, 0))) {
                    activity.startActivity(intent)
                    return
                }
            }
            // open our own Activity to show the URL
            intent = Intent(activity, WebViewActivity::class.java)
            WebViewActivity.prepareIntent(intent, finalWebsiteUrl)
            activity.startActivity(intent)
        }
    }
    val uri = Uri.parse(finalWebsiteUrl)
    val intentBuilder = CustomTabsIntent.Builder()
    val customTabsIntent = intentBuilder.build()
    customTabsIntent.intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_NO_HISTORY
            or Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET or Intent.FLAG_ACTIVITY_MULTIPLE_TASK)
    CustomTabActivityHelper.openCustomTab(activity, customTabsIntent, uri, webviewFallback)
}

回答by Sanket

other option In Load Url in Same Application using Webview

使用 Webview 在同一应用程序中加载 URL 中的其他选项

webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://www.google.com");

回答by Aristo Michael

You can also go this way

你也可以这样走

In xml :

在 xml 中:

<?xml version="1.0" encoding="utf-8"?>
<WebView  
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />

In java code :

在java代码中:

public class WebViewActivity extends Activity {

private WebView webView;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.webview);

    webView = (WebView) findViewById(R.id.webView1);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.loadUrl("http://www.google.com");

 }

}

In Manifest dont forget to add internet permission...

在清单中不要忘记添加互联网权限...

回答by Gorav Sharma

Webview can be used to load Url in your applicaion. URL can be provided from user in text view or you can hardcode it.

Webview 可用于在您的应用程序中加载 Url。URL 可以在文本视图中由用户提供,也可以硬编码。

Also don't forget internet permissions in AndroidManifest.

也不要忘记 AndroidManifest 中的互联网权限。

String url="http://developer.android.com/index.html"

WebView wv=(WebView)findViewById(R.id.webView);
wv.setWebViewClient(new MyBrowser());
wv.getSettings().setLoadsImagesAutomatically(true);
wv.getSettings().setJavaScriptEnabled(true);
wv.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
wv.loadUrl(url);

private class MyBrowser extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
}