如何从内置 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
尝试这个:
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(browserIntent);
这对我来说很好。
至于丢失的“http://”,我会做这样的事情:
if (!url.startsWith("http://") && !url.startsWith("https://"))
url = "http://" + url;
我也可能会预先填充用户正在使用“http://”输入 URL 的 EditText。
实现此目的的常用方法是使用以下代码:
String url = "http://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")));
简单的答案
您可以看到 the official sample from 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);
}
}
这个怎么运作
请看一下 Intent
的构造函数:
public Intent (String action, Uri uri)
您可以将 android.net.Uri
实例传递给第二个参数,并根据给定的数据 url 创建一个新的 Intent。
然后,只需调用 startActivity(Intent intent)
即可启动一个新 Activity,该 Activity 与具有给定 URL 的 Intent 捆绑在一起。
我需要 if check 语句吗?
是的。 docs 说:
如果设备上没有可以接收隐式 Intent 的应用程序,您的应用程序将在调用 startActivity() 时崩溃。要首先验证应用是否存在以接收 Intent,请在 Intent 对象上调用 resolveActivity()。如果结果为非空,则至少有一个应用程序可以处理该意图,并且调用 startActivity() 是安全的。如果结果为 null,则不应使用该意图,并且如果可能,您应该禁用调用该意图的功能。
奖金
您可以在创建 Intent 实例时写一行,如下所示:
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
在 2.3 中,我的运气更好
final Intent intent = new Intent(Intent.ACTION_VIEW).setData(Uri.parse(url));
activity.startActivity(intent);
区别在于使用 Intent.ACTION_VIEW
而不是字符串 "android.intent.action.VIEW"
尝试这个:
Uri uri = Uri.parse("https://www.google.com");
startActivity(new Intent(Intent.ACTION_VIEW, uri));
或者,如果您想在您的活动中打开网络浏览器,请执行以下操作:
WebView webView = (WebView) findViewById(R.id.webView1);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
webView.loadUrl(URL);
如果您想在浏览器中使用缩放控制,那么您可以使用:
settings.setSupportZoom(true);
settings.setBuiltInZoomControls(true);
如果您想向用户显示与所有浏览器列表的对话,那么他可以选择首选,这里是示例代码:
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 :)
}
http
或 https
开头 ether,并且在 java 中,将“魔术字符串”声明为常量是一个好习惯。
context.startActivity
。从外部类调用它时非常有用
Kotlin 的回答:
val browserIntent = Intent(Intent.ACTION_VIEW, uri)
ContextCompat.startActivity(context, browserIntent, null)
我在 Uri
上添加了一个扩展程序,使这更容易
myUri.openInBrowser(context)
fun Uri?.openInBrowser(context: Context) {
this ?: return // Do nothing if uri is null
val browserIntent = Intent(Intent.ACTION_VIEW, this)
ContextCompat.startActivity(context, browserIntent, null)
}
作为奖励,这是一个简单的扩展函数,可以安全地将 String 转换为 Uri。
"https://stackoverflow.com".asUri()?.openInBrowser(context)
fun String?.asUri(): Uri? {
return try {
Uri.parse(this)
} catch (e: Exception) {
null
}
}
就像其他人写的解决方案(工作正常)一样,我想回答同样的问题,但我认为大多数人更愿意使用一个技巧。
如果您希望开始在新任务中打开的应用程序独立于您自己的,而不是停留在同一个堆栈上,您可以使用以下代码:
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);
还有一种方法可以在 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)
}
FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET
已弃用
其他选项 In Load Url in Same Application using Webview
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://www.google.com");
.setJavaScriptEnabled(true);
很危险。
你也可以这样走
在 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" />
在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");
}
}
在清单中不要忘记添加互联网权限...
Webview 可用于在您的应用程序中加载 Url。用户可以在文本视图中提供 URL,也可以对其进行硬编码。
也不要忘记 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;
}
}
在您的 try 块中,粘贴以下代码,Android Intent 直接使用 URI(统一资源标识符)大括号内的链接来识别链接的位置。
你可以试试这个:
Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(myIntent);
一个简短的代码版本...
if (!strUrl.startsWith("http://") && !strUrl.startsWith("https://")){
strUrl= "http://" + strUrl;
}
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(strUrl)));
简单和最佳实践
方法一:
String intentUrl="www.google.com";
Intent webIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(intentUrl));
if(webIntent.resolveActivity(getPackageManager())!=null){
startActivity(webIntent);
}else{
/*show Error Toast
or
Open play store to download browser*/
}
方法二:
try{
String intentUrl="www.google.com";
Intent webIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(intentUrl));
startActivity(webIntent);
}catch (ActivityNotFoundException e){
/*show Error Toast
or
Open play store to download browser*/
}
Fragment
中使用 context!!.packageManager
而不是 getPackageManager()
。
所以我找了很长时间,因为所有其他答案都是为该链接打开默认应用程序,而不是默认浏览器,这就是我想要的。
我终于设法做到了:
// 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 方法,如果您在活动中执行此操作,则不需要它。
String url = "http://www.example.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
简短而甜蜜的 Kotlin 辅助函数:
private fun openUrl(link: String) =
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(link)))
Intent getWebPage = new Intent(Intent.ACTION_VIEW, Uri.parse(MyLink));
startActivity(getWebPage);
MarkB的反应是对的。就我而言,我使用的是 Xamarin,与 C# 和 Xamarin 一起使用的代码是:
var uri = Android.Net.Uri.Parse ("http://www.xamarin.com");
var intent = new Intent (Intent.ActionView, uri);
StartActivity (intent);
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
简单,通过意图查看网站,
Intent viewIntent = new Intent("android.intent.action.VIEW", Uri.parse("http://www.yoursite.in"));
startActivity(viewIntent);
使用这个简单的代码在 android 应用程序中查看您的网站。
在清单文件中添加互联网权限,
<uses-permission android:name="android.permission.INTERNET" />
在 Android 11 中从 URL 打开链接的一种新的更好的方法。
try {
val intent = Intent(ACTION_VIEW, Uri.parse(url)).apply {
// The URL should either launch directly in a non-browser app
// (if it’s the default), or in the disambiguation dialog
addCategory(CATEGORY_BROWSABLE)
flags = FLAG_ACTIVITY_NEW_TASK or FLAG_ACTIVITY_REQUIRE_NON_BROWSER or
FLAG_ACTIVITY_REQUIRE_DEFAULT
}
startActivity(intent)
} catch (e: ActivityNotFoundException) {
// Only browser apps are available, or a browser is the default app for this intent
// This code executes in one of the following cases:
// 1. Only browser apps can handle the intent.
// 2. The user has set a browser app as the default app.
// 3. The user hasn't set any app as the default for handling this URL.
openInCustomTabs(url)
}
参考:
https://medium.com/androiddevelopers/package-visibility-in-android-11-cc857f221cd9 和 https://developer.android.com/training/package-visibility/use-cases#avoid-a-disambiguation-dialog
我检查了每个答案,但是哪个应用程序具有与用户想要使用的相同 URL 的深层链接?
今天我收到了这个案例,答案是browserIntent.setPackage("browser_package_name");
例如:
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
browserIntent.setPackage("com.android.chrome"); // Whatever browser you are using
startActivity(browserIntent);
根据 Mark B 的回答和下面的评论:
protected void launchUrl(String url) {
Uri uri = Uri.parse(url);
if (uri.getScheme() == null || uri.getScheme().isEmpty()) {
uri = Uri.parse("http://" + url);
}
Intent browserIntent = new Intent(Intent.ACTION_VIEW, uri);
if (browserIntent.resolveActivity(getPackageManager()) != null) {
startActivity(browserIntent);
}
}
自 Api level 1
(Android 1.0) 以来,android.webkit.URLUtil
的方法 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
code 了解更多信息。
只需简单地在浏览器中打开您的网址:
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("YourUrlHere"));
startActivity(browserIntent);
String url = "https://www.thandroid-mania.com/";
if (url.startsWith("https://") || url.startsWith("http://")) {
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}else{
Toast.makeText(mContext, "Invalid Url", Toast.LENGTH_SHORT).show();
}
该错误是由于 URL 无效而发生的,Android 操作系统无法为您的数据找到操作视图。所以你已经验证了 URL 是否有效。
科特林
startActivity(Intent(Intent.ACTION_VIEW).apply {
data = Uri.parse(your_link)
})
我认为这是最好的
openBrowser(context, "http://www.google.com")
将以下代码放入全局类
public static void openBrowser(Context context, String url) {
if (!url.startsWith("http://") && !url.startsWith("https://"))
url = "http://" + url;
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
context.startActivity(browserIntent);
}
这种方式使用一种方法,允许您输入任何字符串而不是固定输入。如果重复使用,这确实会节省一些代码行,因为您只需要三行来调用该方法。
public Intent getWebIntent(String url) {
//Make sure it is a valid URL before parsing the URL.
if(!url.contains("http://") && !url.contains("https://")){
//If it isn't, just add the HTTP protocol at the start of the URL.
url = "http://" + url;
}
//create the intent
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)/*And parse the valid URL. It doesn't need to be changed at this point, it we don't create an instance for it*/);
if (intent.resolveActivity(getPackageManager()) != null) {
//Make sure there is an app to handle this intent
return intent;
}
//If there is no app, return null.
return null;
}
使用这种方法使其普遍可用。 IT 不必放在特定的活动中,因为您可以像这样使用它:
Intent i = getWebIntent("google.com");
if(i != null)
startActivity();
或者,如果您想在活动之外启动它,只需在活动实例上调用 startActivity:
Intent i = getWebIntent("google.com");
if(i != null)
activityInstance.startActivity(i);
正如在这两个代码块中看到的那样,有一个空检查。这是因为如果没有应用程序来处理意图,它会返回 null。
如果没有定义协议,则此方法默认为 HTTP,因为有些网站没有 SSL 证书(您需要 HTTPS 连接),如果您尝试使用 HTTPS 但它不存在,这些网站将停止工作.任何网站仍然可以强制使用 HTTPS,因此无论哪种方式,这些方面都会让您使用 HTTPS
由于此方法使用外部资源显示页面,因此无需您声明 Internet 权限。显示网页的应用程序必须这样做
http://
方案 - 显示的异常表明您的 URL 缺少该方案。if (!url.startsWith("http://") && !url.startsWith("https://"))
是一个常见错误,它可能会导致您访问像 file:// 这样的网址并破坏一些好的用例。尝试使用 URI 类解析 uri 并检查是否存在模式。如果没有,请添加“http://”;)resolveCheck
进行空检查。请参阅offical docs:注意:如果设备上没有可以接收隐式 Intent 的应用程序,则您的应用程序在调用 startActivity() 时会崩溃。要首先验证是否存在接收 Intent 的应用,请在 Intent 对象上调用 resolveActivity()。