Chrome Custom Tabs — Kotlin and Lifecycle Aware

Saurabh Arora
AndroidPub
Published in
2 min readAug 18, 2018

Recently, I needed to integrate Chrome Custom Tabs into our app. We wanted to warmup the browser and pre-render the content as we were in situations where we were certain that the user would go ahead and open the url. Upon going through the documentation, I came across the demo app by Google which shows how to integrate the library and perform the warmup and pre-render. While browsing the source code, two things stuck out:

  • The user needs to to handle lifecycle events and manage the binding and unbinding of the Custom Tabs Service. This is a detail that can be abstracted away from the user.
  • The helper classes are in Java. If they were in Kotlin, we could have a shorter and cleaner API.
Verbose Java code to start ChromeCustomTabs. Notice the nulls in `mayLaunchUrl`

To ease the integration with Chrome Custom Tabs, I quickly wrote up a version of the helpers offered by Google, in Kotlin and made it lifecycle aware.

The new library abstracts away the service binding logic by using a LifecycleObserver.

It also adds in an extension function on the CustomTabsIntent to launch the custom tabs with a fallback mechanism, i.e. since not all devices have the Chrome Browser, the fallback is called so that you can chose to handle the url differently, like open it in a webview.

Concise and Lifecycle dependent Kotlin code

Designing lifecycle aware components can really help in reducing boilerplate code and make it extremely easier for users to integrate your library! So whenever you need the user to take some action in lifecycle callbacks, remember that you are asking the user to do unnecessary work and that should really be your job and not the users.

Checkout the source code here.
Follow me on twitter here.

If you like the post, don’t forget to send some claps :)

--

--