这个问题在这里已经有了答案:如何从我的应用程序中打开 Android 的网络浏览器中的 URL? (41 个回答) 8 年前关闭。
我只是想知道如何启动手机浏览器的 Intent 以打开特定的 URL 并显示它。
有人可以给我一个提示吗?
要打开 URL/网站,请执行以下操作:
String url = "http://www.example.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
这是documentation of Intent.ACTION_VIEW
。
来源:Opening a URL in Android's web browser from within application
短版
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://almondmendoza.com/android-applications/")));
应该也可以...
最短的版本。
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com")));
在某些情况下,URL 可能以“www”开头。在这种情况下,你会得到一个例外:
android.content.ActivityNotFoundException: No Activity found to handle Intent
URL 必须始终以“http://”或“https://”开头,所以我使用这段代码:
if (!url.startsWith("https://") && !url.startsWith("http://")){
url = "http://" + url;
}
Intent openUrlIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(openUrlIntent);
Matcher _SCHEMA_MATCHER = Pattern.compile("(https?://|mailto:).+").matcher("")
并返回 _SCHEMA_MATCHER.reset(uri).matches()? uri : "http://" + uri
。
向浏览器发送 Intent 以打开特定 URL:
String url = "https://www.stackoverflow.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
可以更改为短代码版本...
Intent intent = new Intent(Intent.ACTION_VIEW).setData(Uri.parse("http://www.stackoverflow.com"));
startActivity(intent);
或者
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.stackoverflow.com"));
startActivity(intent);
甚至更短!
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.stackoverflow.com")));
关于 Intent 的更多信息
=)
还有一种方法可以将坐标直接传递给谷歌地图进行显示吗?
您可以使用 geo URI
前缀:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("geo:" + latitude + "," + longitude));
startActivity(intent);
从 XML
如果您的视图中显示了网址/URL,并且您希望它使其可点击并将用户定向到特定网站,您可以使用:
android:autoLink="web"
以同样的方式,您可以使用 autoLink 的不同属性(电子邮件、电话、地图、所有)来完成您的任务......
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(browserIntent);
在您的代码中使用以下代码段
Intent newIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse("https://www.google.co.in/?gws_rd=cr"));
startActivity(newIntent);
使用此链接
http://developer.android.com/reference/android/content/Intent.html#ACTION_VIEW
“还有没有办法将坐标直接传递给谷歌地图显示?”
我发现如果我将包含坐标的 URL 传递给浏览器,只要用户没有选择浏览器作为默认浏览器,Android 就会询问我是想要浏览器还是地图应用程序。有关 URL 格式的更多信息,请参阅我的回答 here。
我想如果你使用一个意图来启动带有坐标的地图应用程序,那也可以。
http
或https
开头...最好检查if (!url.startsWith("http://") && !url.startsWith("https://")) url = "http://" + url;