美文网首页
Android本地浏览器打开网址

Android本地浏览器打开网址

作者: 喂_balabala | 来源:发表于2023-06-03 00:13 被阅读0次
  • 除非指定浏览器打开某个网址,否则其他方式有个前提,就是必须协议开头才能识别为是网址,才会用浏览器打开,不然是无响应的

方式一:

var urlString = "www.aa.bb"
if (!urlString.startsWith("http://") && !urlString.startsWith("https://")) {
    urlString = "http://$urlString"
}
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(urlString))
//intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
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.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
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")) {
        // 这里的 componentName 就是本地浏览器的 ComponentName
        val componentName = ComponentName(activity.activityInfo.packageName, activity.activityInfo.name)
        intent.component =componentName
        startActivity(intent)
    }
}

相关文章

网友评论

      本文标题:Android本地浏览器打开网址

      本文链接:https://www.haomeiwen.com/subject/vkwmedtx.html