简体   繁体   English

为什么 CustomTabsClient.bindCustomTabsService 不起作用?

[英]Why won't CustomTabsClient.bindCustomTabsService work?

I've recently been working on adding some Chrome Custom Tabs to my Android app and for some reason, I can't bind to the CustomTabsService.我最近一直致力于将一些Chrome 自定义选项卡添加到我的 Android 应用程序中,由于某种原因,我无法绑定到 CustomTabsService。

  • I have an updated version of Chrome我有 Chrome 的更新版本
  • Android Gradle Plugin Version 4.0.0 Android Gradle 插件版本 4.0.0
  • Gradle Version 6.1.1 Gradle 版本 6.1.1

I've added Log calls to see if my connection was successful but it never is.我添加了日志调用以查看我的连接是否成功,但它从来没有成功。 I'm trying to take action based on the user's navigation within the CustomTabs by using the CustomTabsCallback but I need to connect to the service first.我正在尝试使用 CustomTabsCallback 根据用户在 CustomTabs 中的导航采取行动,但我需要先连接到服务。 Any help is appreciated!任何帮助表示赞赏!

Dependencies依赖项

// Custom Tabs
    implementation 'androidx.browser:browser:1.3.0-alpha01'
    implementation 'com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava'

I've also tried with this (current versions are here ):我也试过这个(当前版本在这里):

implementation 'androidx.browser:browser:1.2.0'

CustomTabsFragment自定义标签片段

package com.mullr.rabbithole.ui.dig

import android.app.Service
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.content.res.AppCompatResources
import androidx.browser.customtabs.*
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.DrawableCompat
import androidx.core.graphics.drawable.toBitmap
import com.mullr.rabbithole.R
import com.mullr.rabbithole.main.MainActivity
import kotlinx.android.synthetic.main.dig_fragment.*

private lateinit var main: MainActivity

class DigTabs : Fragment() {

    // Custom Tabs
    lateinit var client: CustomTabsClient
    lateinit var session: CustomTabsSession
    lateinit var serviceConnection: CustomTabsServiceConnection
    var builder = CustomTabsIntent.Builder()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        main = requireActivity() as MainActivity

       serviceConnection = object : CustomTabsServiceConnection() {
            override fun onCustomTabsServiceConnected(name: ComponentName, mClient: CustomTabsClient) {
                Log.d("Service", "Connected")
                client = mClient
                client.warmup(0L)
                val callback = RabbitCallback()
                session = mClient.newSession(callback)!!
                builder = CustomTabsIntent.Builder(session);
            }

            override fun onServiceDisconnected(name: ComponentName?) {

            }
        }

        Log.d("start", "attempt")
        // Connect to service
        var ok =  CustomTabsClient.bindCustomTabsService(main, main.packageName, serviceConnection)
        if (ok) {
            Log.d("start", "connected")
        } else {
            Log.d("start", ok.toString())
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_dig_tabs, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        wiki_button.setOnClickListener {
            var url = "https://www.wikipedia.org/"
            loadCustomTab(url)
        }

        google_button.setOnClickListener {
            var url = "https://www.google.com"
            loadCustomTab(url)
        }
    }

    fun loadCustomTab(url: String) {
        builder.setSecondaryToolbarColor(ContextCompat.getColor(main, R.color.colorAccent))
        builder.setToolbarColor(
            ContextCompat.getColor(
                main,
                R.color.black
            )
        ) // Change tab toolbar color
        builder.setShowTitle(true)
        builder.addDefaultShareMenuItem()
        builder.enableUrlBarHiding()
        AppCompatResources.getDrawable(main, R.drawable.close_icon)?.let {
            DrawableCompat.setTint(it, Color.WHITE)
            builder.setCloseButtonIcon(it.toBitmap())
        }
        val customTabsIntent: CustomTabsIntent = builder.build()
        customTabsIntent.launchUrl(main, Uri.parse(url))
    }

    override fun onDestroy() {
        super.onDestroy()
        main.unbindService(serviceConnection)
    }

    class RabbitCallback : CustomTabsCallback() {
        override fun onNavigationEvent(navigationEvent: Int, extras: Bundle?) {
            super.onNavigationEvent(navigationEvent, extras)
            Log.d("Nav", "test")
            when (navigationEvent) {
                1 -> Log.d("Navigation", "Start")
                NAVIGATION_FINISHED -> Log.d("Navigation", "Finished")
                NAVIGATION_FAILED -> Log.d("Navigation", "Failed")
                NAVIGATION_ABORTED -> Log.d("Navigation", "Aborted")
                TAB_SHOWN -> Log.d("Navigation", "Tab Shown")
                TAB_HIDDEN -> Log.d("Navigation", "Tab Hidden")
                else -> Log.d("Navigation", "Else")
            }
        }
    }
}

This turned out to be a silly mistake.结果证明这是一个愚蠢的错误。 The CustomTabsClient.bindCustomTabsService method needs the package name of the Custom Tabs service and not the package of the calling activity. CustomTabsClient.bindCustomTabsService 方法需要自定义选项卡服务的 package 名称,而不是调用活动的 package。 So this...所以这...

var ok =  CustomTabsClient.bindCustomTabsService(main, main.packageName, serviceConnection)

Should be...应该...

var ok =  CustomTabsClient.bindCustomTabsService(main, "com.android.chrome", serviceConnection)

Possible package names can be found here .可以在此处找到可能的 package 名称。 They include:他们包括:

  • com.android.chrome com.android.chrome
  • com.chrome.beta com.chrome.beta
  • com.chrome.dev com.chrome.dev

Android 11 has introduced package visibility changes. Android 11 引入了 package 可见性更改。 If your Android app is targeting API level 30 or above, adding a queries section to AndroidManifest.xml is needed, otherwise the code snippet above won't return results:如果您的 Android 应用程序的目标是 API 级别 30 或更高,请在 AndroidManifest.xml 中添加查询部分,否则需要返回结果:否则上面的代码片段不会返回

<queries>
    <intent>
        <action android:name=
            "android.support.customtabs.action.CustomTabsService" />
    </intent>
</queries>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM