くうと徒然なるままに

モバイルアプリを作りながらバックエンドも作っています。

Chrome Custom Tabs の Pre Fetch を Kotlin っぽく書いてみた。

Chrome Custom Tabs には Pre Fetch という機能が存在します。 これは、 Chrome Custom Tabs でウェブページを表示する前に事前に読み込んでおくことで表示速度の最適化を行える機能です。

自前実装しようとすると大変なこの機能ですが、 Google Chrome の機能を使うことで簡略に実装することができます。

ウェブ上にあるサンプルをググってもJava で書かれているものが多く精神衛生上よくありません。

ということで、Kotlin っぽく書いてみます。

class Fragment : Fragment() {
    private var customTabsClient: CustomTabsClient? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        bindCustomTabsService(
            requireContext(),
            requireContext().packageName,
            object : CustomTabsServiceConnection() {
                override fun onCustomTabsServiceConnected(
                    name: ComponentName?,
                    client: CustomTabsClient?
                ) {
                    customTabsClient = client
                    client?.warmup(0)
                }

                override fun onServiceDisconnected(name: ComponentName?) {
                    customTabsClient = null
                }
            }
        )
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
// 省略
            customTabsClient?.let {
                val session = it.newSession(object : CustomTabsCallback() {})
                session.mayLaunchUrl(Uri.parse("www.google.com"), null, null) 
            }

        return binding.root
    }
}