Android 自定义选项卡 - 防止 launchUrl() 打开默认应用程序,强制应用程序内自定义选项卡浏览器

问题描述 投票:0回答:2

.launchUrl(this@MainActivity, Uri.parse(url))

url
https://www.amazon.com
时,将打开 Amazon 应用程序而不是自定义选项卡浏览器。有什么方法可以防止这种情况发生并强制使用自定义选项卡浏览器而不是默认应用程序?

android chrome-custom-tabs
2个回答
0
投票

如果您将 chrome 包添加到自定义选项卡意图中,它将打开自定义选项卡而不是应用程序,即

tabsIntent.intent.setPackage("com.android.chrome");
在打电话之前
tabsIntent.launchUrl(context, Uri.parse("https://www.amazon.com"));

但是如果未安装 Google Chrome,应用程序将会崩溃。


0
投票

我在这里找到了这个

…将 CustomTabsSession 传递给 CustomTabIntent 将强制打开自定义选项卡中的链接,即使安装了相应的本机应用程序也是如此。

按照本指南,我想出了以下经理课程:

class CustomTabSessionManager { private var mClient: CustomTabsClient? = null var mSession: CustomTabsSession? = null private val mConnection: CustomTabsServiceConnection = object : CustomTabsServiceConnection() { override fun onCustomTabsServiceConnected( name: ComponentName, client: CustomTabsClient ) { // Warm up the browser process client.warmup(0 /* placeholder for future use */) // Create a new browser session mSession = client.newSession(CustomTabsCallback()) mClient = client } override fun onServiceDisconnected(name: ComponentName) { mClient = null mSession = null } } fun bindCustomTabService(context: Context) { // Check for an existing connection if (mClient != null) { // Do nothing if there is an existing service connection return } // Get the default browser package name, this will be null if // the default browser does not provide a CustomTabsService val packageName = CustomTabsClient.getPackageName(context, null) ?: // Do nothing as service connection is not supported return CustomTabsClient.bindCustomTabsService(context, packageName, mConnection) } }
在我的主要活动中我会:

class MainActivity : AppCompatActivity() { private val customTabSessionManager = CustomTabSessionManager() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // ... customTabSessionManager.bindCustomTabService(this) } fun getCustomTabSession(): CustomTabsSession? = customTabSessionManager.mSession }
然后,只要您想打开自定义选项卡,您就可以获取会话:

val session = (requireActivity() as? MainActivity)?.getCustomTabSession() CustomTabsIntent .Builder(session) .build() .launchUrl(requireContext(), "https://www.example.com/")
不要忘记将以下内容添加到您的清单中:

<manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"> … <queries> <intent> <action android:name="android.support.customtabs.action.CustomTabsService" /> </intent> </queries> </manifest>
    
© www.soinside.com 2019 - 2024. All rights reserved.