Add Chrome Custom Tabs to the Android Jetpack Navigation Component
Published: 2021-03-09 19:14:20

With the introduction of [Android Jetpack](https://oliverspryn.link/android-jetpack), developers now have a marvelous new set of libraries which offer an unprecedented level of simplicity and reusability. Before Jetpack's debut, fragment and activity-based navigation often proved to be complicated, fragile, and nearly unique to each app on the market. Google has heard our pleas for help and given us the [Navigation Component](https://oliverspryn.link/android-navigation-component).

# Current State of the Navigation Component

Since the preliminary release of the navigation component in May 2018, much of its functionality has improved, changed, and expanded. As of November 2020, the current state of this library offers native support for [these destination types](https://oliverspryn.link/android-navigation-component-built-in-destinations):

- Fragments
- Activities
- DialogFragments

Support for [Chrome Custom Tabs](https://oliverspryn.link/chrome-custom-tabs) (CCT) is a notable omission from this list. Fortunately, since CCT is similar enough in behavior to activities, it is not a significant lift to add in support for this destination type.

# Getting Our Thinking Straight

CCT can almost feel like magic. It is an activity which manages all of the back and forward functionality a user would expect in a normal browser without an engineer having to hijack the system's back button or listen for an event when closing the browser with the X icon. Once the user finishes, he or she is dropped back onto the previous fragment or activity, just as expected.

In general, however, the navigation component was designed to handle switching out multiple fragments on a single activity. Therefore, when adding in CCT as a destination type, an engineer must keep in mind that the graph has no control over the browser and should not consider adding it to the component's built-in back stack. Why? As will be the answer for most things in this article, it is because the browser handles this functionality entirely on its own, like a black box. This fact dramatically reduces the effort on our part to add in this capability.

![A Google Pixel 2XL on a marble surface](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ordpst63o4raxrehzx0y.jpg)

---

# What is Required?

To declare a custom destination type for the Jetpack Navigation Component, an engineer needs to create three files:

1. `values/attrs.xml` - Holds the XML definition of the destination type for Android Studio code completion and to support custom attributes.
1. Custom Navigator Class - Defines how to navigate into (push) and out of (pop) the custom destination. Also maps the custom attributes from the XML file to the code which implements and uses those properties.
1. Custom Navigator Host - Adds support for the custom destination to the navigation controller.

Of course, before writing extensions for the navigation graph, you'll need to have it included as part of your project and use Android Studio 3.3 or newer. Head over the Android documentation to learn how to set up the [Navigation Component](https://oliverspryn.link/import-android-navigation-component) with [Safe Args](https://oliverspryn.link/import-safe-args).

# Define the Schema

Technically speaking, all "destination types" are a subtype of the `Navigator<D extends NavDestination>` class. Thus, let's create a new class called `ChromeCustomTabsNavigator`, let it inherit from `Navigator`, and stub all of the abstract methods.

We will, of course, have to supply a type to the generic argument for the `Navigator`. In practice, engineers typically create a nested class inside of the first class, call it `Destination`, subclass it from `NavDestination`, and supply the stubbed navigator as a constructor parameter.

Now, the generic argument for the Navigator can receive the nested class. Altogether, the basic implementation looks like this:

{% gist https://gist.github.com/oliverspryn/46d9cce1b446d35881bd981affa65fcc %}

Depending on your needs, you may not need a `context` as a constructor argument. I, however, know that it will be necessary for this example, so I added it up front.

You probably noticed two decorators in the above code sample. Here is what they do:

- `@Navigator.Name("chrome")` — Defines the name of the tag which we will use in the navigation graph’s XML file. Thus, in this case, I will use the destination type as `<chrome ... />`.
- `@NavDestination.ClassType(Activity::class)` — Provides the component with some insight regarding what kind of destination you are implementing. Since CCT is an activity, I supplied `Activity::class` as the destination type.

![A developer workstation with two monitors, headphones, and an iPhone](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2i35r2r8z80h9jg354ln.jpg)

# Declare Customization Properties

In this example, I would like to pass two styling attributes from my navigation's XML file to the destination. Proper support for that feature starts by creating an `attrs.xml` file under the `values` resource folder. This chore should feel familiar if you have ever built a custom component for Android.

I would like to set the [CCT toolbar and secondary toolbar colors](https://oliverspryn.link/chrome-custom-tabs-toolbar-color). Thus, my `attrs.xml` file looks like this, with two properties which supply code completion for an Android reference type.

{% gist https://gist.github.com/oliverspryn/18be2c9ef5f0fbeb48bfbb698bc5074f %}

Notice how, by convention, the name of the `declare-styleable` matches the name of the custom navigator. You could name it something different if that make more sense in your case. However, the naming here seems to fit this example.

---

# Fetch the Custom Properties

Now that our schema is fully defined, we can begin to use these parameters in our code.

Android uses the `ChromeCustomTabsNavigator.Destination` to fetch and map these properties to code. Let’s expand our `Destination` class to add the necessary support.

First, let’s add two properties, one for each parameter:

{% gist https://gist.github.com/oliverspryn/c61f1725a0163797071eaa7e6a619ad9 %}

Then, override the `onInflate()` method to fetch these properties from the XML and set them:

{% gist https://gist.github.com/oliverspryn/99c2d08851ebd917a50d422df8da599f %}

Notice the convention for fetching each property from the XML file. The convention is `R.styleable.<styleable name>_<attribute name>`. I have found that you may need to do a build before Android Studio offers autocompletion for these values.

If you are having trouble finding the `withStyledAttributes` method, make sure you’ve included [AndroidX Core-ktx](https://oliverspryn.link/android-core-ktx) in your Gradle configuration: `androidx.core:core-ktx:$latest-version`.

![The home screen of a Samsung Galaxy phone](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oymggy0oa6wizpfr6s4b.jpg)

# Populate the Navigator

Now that the foundation for the navigator is in place, it is time to populate the navigator's stubs. Starting with the two easiest methods, let's populate the `createDestination()` and `popBackStack()` methods:

{% gist https://gist.github.com/oliverspryn/ad4afee68aa64b6a5a610d4dff97c250 %}

The first method, `createDestination()`, is fairly self-explanatory since it simply returns an instance of the custom `Destination` class. The `popBackStack()` method, in most cases, returns `false` whenever the method handles the back stack operation itself, and `true` if nothing remains on the stack for the method to pop.

Since CCT is an activity with its own fully-managed back stack, there is nothing for the navigation graph to do. By the time CCT pops itself off the stack, drops the user back onto the prior view, and the navigation graph is reactivated, all back navigation has been handled for free. Thus, `popBackStack()` always returns `true`.

Now, let’s tackle the `navigate()` method:

{% gist https://gist.github.com/oliverspryn/4aa0ff2c4262a3979dc6aee66ff6e17b %}

The `navigate()` method simply wraps CCT’s builder and launch methods, [as described in their documentation](https://oliverspryn.link/open-chrome-custom-tab). The toolbar colors are extracted from the properties of the custom `Destination` class we wrote earlier and applied to the builder. Last, the argument bundle extracts a URI, casts it, and passes it to the launch procedure.

Once again, since CCT manages its own back stack, we do not return any kind of `NavDestination`. Since we return `null`, that prevents the navigation graph from adding the CCT destination to its own back stack, and thereby causing some weird back press behavior.

That was the hard part. Here is the navigator in its full glory:

{% gist https://gist.github.com/oliverspryn/60025b9a0bb6191d044b82f6a3b0d0a0 %}

---

# Create a Navigation Host

The built-in navigation host only supports the kind of [destinations which ship with the navigation component](https://oliverspryn.link/android-navigation-component-built-in-destinations), namely:

- Fragments
- Activities
- DialogFragments

However, we will probably have a graph which contains not only our custom destination type, but also a mix of the above destinations. Thus, we will need to subtype the built-in navigation host, and shim in support for the `ChromeCustomTabsNavigator`.

This turns out to be quite easy. As described in [Google's documentation](https://oliverspryn.link/new-destination-types), you probably are already using the `NavHostFragment`, which supports all of the built-in destinations. That is an ideal candidate as our base class. Let’s subclass it, and override the `onCreateNavController()` method, where we add support for our new destination:

{% gist https://gist.github.com/oliverspryn/af459df97b3481c0c3e9357e8fb387a0 %}

If we do not explicitly add in this type of support, the navigation graph will throw an exception and say that it cannot handle your custom destination. Fortunately, all of the hard work is already handled by the `NavHostFragment`, making this process extremely simple. Notice how the `context` is given to the navigator by the host.

That class is the final piece of the puzzle. Let’s start using our new destination!

![A Samsung tablet sitting on a travel bag](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eqcs48kms9p81soyw793.jpg)

---

# Putting it All Together

In this example, I'll create a simple activity, which contains only the navigator host. We will have to use our custom host in our activity layout file:

{% gist https://gist.github.com/oliverspryn/f1b59a9384ee4afc14e94d7fecbaf21e %}

The only aspect of the above code which changes from the documentation is the `android:name` property, to point to our custom navigator host. The rest of the code sample is derived from [the relevant Google documentation](https://oliverspryn.link/add-a-navigation-host-fragment).

Next, we will need to add a CCT destination to our graph. Again, referring to [the documentation](https://oliverspryn.link/navigation-graph-destinations), we can build up our graph with activities, fragments, and dialog fragments. Let’s add in a link to CCT:

{% gist https://gist.github.com/oliverspryn/eb8c6dd70f5c317b29678952fe9bdd56 %}

We could have written our implementation so that the URL was provided as an attribute in the XML. However, since I wanted more flexibility, my implementation uses arguments to pass along this information. To send this necessary information to CCT, add in an action with an argument:

{% gist https://gist.github.com/oliverspryn/5d74b8d4b6e2f86d40ac716bd560536a %}

Then, we can pass the information along via a safe arg, just as [described in the documentation](https://oliverspryn.link/pass-data-with-safe-args). Assuming you do your routing from the `MainActivity`, your implementation will look similar to this:

{% gist https://gist.github.com/oliverspryn/0d2304bcc9a39c2e94a6dbe63f784313 %}

Now, since the safe arg is passed as a bundle to the `ChromeCustomTabsNavigator`, the bundle is unwrapped and the `uri` parameter is extracted, as shown earlier in [our implementation](https://oliverspryn.link/receive-the-uri-parameter) above.

Viola! We have a fully working custom destination which opens Chrome Custom Tabs, integrates into the navigation graph, and preserves the back button functionality in Android.

# Expansion and Usage in Production

There are plenty of ways this example can be modified and expanded to include more powerful functionality. Before we say 👋, you may be interested to see how this is used in a production app.

Here is a screenshot of how the CCT destination works in one of the modules of the [MyUPMC app](https://oliverspryn.link/myupmc-android):

![A working graph with fragments, an activity, and three CCT destinations](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/czc72s99gzkkh6kj4ozm.png)

The orange screens are the CCT destinations. For visual clarity, I created a simple layout which I do not use within the app, but apply to the graph with the `tools:layout="@layout/graph_placeholder_chrome` property.

Here an example of CCT working within the app:

![The Chrome Custom Tabs component extension in action](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/93bw8lmnjcmnfvdhnlo3.gif)

# Credits

These sources proved themselves to be incredibly helpful as I wrote my first implementation of this new destination type:

- [Android Navigation Component documentation](https://oliverspryn.link/getting-started-with-the-navigation-component)
- [Chrome Custom Tabs documentation](https://oliverspryn.link/chrome-custom-tabs)
- [Custom Dialog Navigator](https://oliverspryn.link/dialog-navigator)
- [Jetpack Navigation with Custom Views](https://oliverspryn.link/jetpack-navigation-with-custom-views)