如何从内置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)
}
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)
}
另外,这里有一个简单的扩展函数,可以将字符串安全地转换为Uri。
"https://stackoverflow.com".asUri()?.openInBrowser(context)
fun String?.asUri(): Uri? {
return try {
Uri.parse(this)
} catch (e: Exception) {
null
}
}
在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-消除歧义对话框