- 除非指定浏览器打开某个网址,否则其他方式有个前提,就是必须协议开头才能识别为是网址,才会用浏览器打开,不然是无响应的
方式一:
var urlString = "www.aa.bb"
if (!urlString.startsWith("http://") && !urlString.startsWith("https://")) {
urlString = "http://$urlString"
}
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(urlString))
context.startActivity(intent)
方式二:
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(urlString))
val chooser = Intent.createChooser(intent, "Open with")
context.startActivity(chooser)
方式三:
- 指定Android系统浏览器,有些手机会修改或删除Android原生浏览器导致崩溃
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(urlString))
intent.component = ComponentName(
"com.android.browser",
"com.android.browser.BrowserActivity"
)
context.startActivity(intent)
方式四:
- 代码找出手机中所有浏览器的ComponentName然后选择一个打开
val url = "https://www.example.com"
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
val activities = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
for (activity in activities) {
if (activity.activityInfo.packageName.contains("browser")) {
val componentName = ComponentName(activity.activityInfo.packageName, activity.activityInfo.name)
intent.component =componentName
startActivity(intent)
}
}