This is the fourth in a series of articles about the Navigation component API and tool. These articles are based on content that is also explained in video form, as part of the MAD Skills series, so feel free to consume this material in whichever way you prefer (though the code tends to be easier to copy from text than from a video, which is why we offer this version as well).

If you prefer your content in video form, here it is:

Introduction

This episode is on Deep Links, the facility provided by Navigation component for easily passing data between destinations.

Sometimes you want to make it easy for the user to get to a specific part inside the flow of your application, without having to click-click-click from the start screen to get there. For example, maybe you want to surface ongoing conversations in a chat app, or the user’s cart in a shopping application. You can use deep links to do this, surfacing these links outside of the application, in shortcuts and notifications, that allow the user to click from those other locations and get to those deeper parts of your app.

Navigation component simplifies creating these deep links. To show how they work, we’re going to take another look at the Donut Tracker app that I used in previous episodes. The finished code for the app is on GitHub; feel free to download and open it up in Android Studio to follow along.

Since the code is done, I’ll walk you through the steps I went through to make it all work.

Donut Deep Linking

In Donut Tracker, there are a couple of actions that are useful to get to quickly. For example, if I have a really good donut in the wild, I’d like to be able to add that information into the list without having to launch the app first and then click on the FloatingActionButton to bring up the data-entry dialog. Also, if I’ve just added or edited information about a donut, I’d like to post a notification so that I can quickly get back to editing that recent entry.

I added deep links for both of these actions: one for adding a new donut and another for returning to an ongoing edit. The “add” action uses an “implicit” deep link. Implicit is what we call a link that takes you to a static location inside your hierarchy, one that does not change over time. In my app, the implicit deep link will always take you to the form that allows you to add a new donut to the list.

The “continue editing” action uses an “explicit” deep link. Explicit is what we call a link that takes you to dynamic content inside your application.

Implicit

Let’s start with an implicit deep link to add a new donut.

First, I needed to create the deep link, which I did in the navigation editor. Clicking on the dialog destination shows the properties of that destination on the right:

Image for post

Clicking on a destination shows its properties, which is where we can create a new deep link to navigate to that destination

I clicked on the + next to Deep Links. This brought up a dialog in which I entered a URI (Universal Resource Identifier). In this case, I wanted a URI that is specific to the app (not a general web address that might be picked up by the browser app), so I used “myapp” as an identifier that is specific to our app:

Image for post

Creating a new deep link brings up a dialog where you enter a URL associated with the deep link to that destination

Next, I edited the application manifest to inform the application that I wanted a shortcut for the deep link:

<activity
    android:name="com.android.samples.donuttracker.MainActivity"
    android:label="@string/app_name"
    android:theme="@style/AppTheme.NoActionBar">
    <nav-graph android:value="@navigation/nav_graph" />
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
    <meta-data android:name="android.app.shortcuts"
        android:resource="@xml/shortcuts" />
</activity>

In that meta-data block, I told the activity that there is information about the deep link in the navigation graph. I also referenced a new file in the xml resource directory with information about an app shortcut for this activity.

I then created the xml folder and a new shortcuts.xml file in that new directory. In the shortcuts file, I entered information about the app shortcut, including the URI we saw above:

<shortcuts
    xmlns:android="http://schemas.android.com/apk/res/android">
  <shortcut
    android:shortcutId="NewDonutDialogFragment"
    android:enabled="true"
    android:shortcutShortLabel="@string/static_shortcut_label_short"
    android:shortcutLongLabel="@string/static_shortcut_label_long"
    android:shortcutDisabledMessage=
        "@string/static_shortcut_disabled_message"
    android:icon="@drawable/donut_with_sprinkles">
    <intent
       android:action="android.intent.action.VIEW"
       android:data="myapp://navdonutcreator.com/donutcreator" />
  </shortcut>
</shortcuts>

The important part here is that data item, which uses the same URI string as I entered into the deep link dialog in the navigation tool earlier. This is the connecting glue which causes navigation to happen from the app shortcut to the dialog destination.

And that’s all I needed for an implicit deep link: I told it the destination to navigate to, created the shortcut to do that navigation, and I was done. If you run the app, you can see the shortcut by long-pressing on the app icon. Clicking that shortcut will take you to the form to create a new donut item.

That was implicit deep links. Now let’s create an explicit deep link, which will be created dynamically based on the state of the app.

Explicit

If you’re like me, then donuts are really important to you. When I’m entering information about a new donut find, I probably want to take my time with it. So I’ll start the entry with some information, but I may want to come back later and enter more when I’ve really had a chance to appreciate the experience.

This can be done with notifications: when I enter information about a donut, the app creates a notification that makes it easier to get back to that ongoing entry. There’s not a lot of code necessary to do this; I just needed to create a notification with a PendingIntent to get to the right place in the application.

Most of this happens in DonutEntryDialogFragment, in the onClick() listener for the Done button. We’ve seen this click listener code in a previous episode; this is where we add new or updated data to the ViewModel. I just needed to add an extra step here to create the notification. The parts in bold are the code I had to add to deal with the notification.

binding.doneButton.setOnClickListener {
    // Grab these now since Fragment may go away before the
    // lambda below is called
    val context = requireContext().applicationContext
    val navController = findNavController()

    donutEntryViewModel.addData(
        donut?.id ?: 0,
        binding.name.text.toString(),
        binding.description.text.toString(),
        binding.ratingBar.rating.toInt()
    ) { actualId ->
        val arg = DonutEntryDialogFragmentArgs(actualId).toBundle()
        val pendingIntent = navController
            .createDeepLink()
            .setDestination(R.id.donutEntryDialogFragment)
            .setArguments(arg)
            .createPendingIntent()

        Notifier.postNotification(actualId, context, pendingIntent)
    }
    dismiss()
}

First, the code creates arg with the donut id to use. This will be used to tell the destination dialog which donut to retrieve that the user will continue editing.

The code then creates pendingIntent for the deep link using an API in NavigationController. The destination is set to be this dialog fragment. The call also sets the argument which holds the ID and create the intent.

Then the code calls Notifer.postNotification(), a utility class/method I created for handling the details of creating and posting the notification.

fun postNotification(id: Long, 
                     context: Context, 
                     intent: PendingIntent) {
    val builder = NotificationCompat.Builder(context, channelId)
    builder.setContentTitle(context
            .getString(R.string.deepLinkNotificationTitle))
        .setSmallIcon(R.drawable.donut_with_sprinkles)
    val text = context.getString(R.string.addDonutInfo)
    val notification = builder.setContentText(text)
        .setPriority(NotificationCompat.PRIORITY_HIGH)
        .setContentIntent(intent)
        .setAutoCancel(true)
        .build()
    val notificationManager =
        NotificationManagerCompat.from(context)
    notificationManager.cancelAll()
    notificationManager.notify(id.toInt(), notification)
}

First, the code creates the notification builder. Note that it needed a channelId to construct the builder, which is created as necessary in the init() function of Notifier (see the code for those details; it’s standard stuff).

I then supplied the necessary data for the notification, set the intent, and built it. Before posting, existing notifications are canceled (I only wanted to be able to edit the latest donut).

Finally, the new notification is posted and… it’s done. Now every new editing operation (whether for a new donut or an existing donut) will surface a notification that the user can click on to get back to that editing action.

Summary

In this episode, I created both an implicit deep link , which takes the user to a static location in the app where they can enter information about a new donut, and an explicit deep link, which allows the user to continue editing an existing donut where they left off.

This Donut Tracker app is getting better and better. Not as good as a donut, of course… but then nothing is.

That’s it for this time. Go grab a donut — you’ve earned it.

For More Information

For more details on Navigation component, check out the guide Get started with the Navigation component on developer.android.com.

To see the finished Donut Tracker app (which contains the code outlined above, but also the code covered in future episodes), check out the GitHub sample.

Finally, to see other content in the MAD Skills series, check out the video playlist in the Android Developers channel on YouTube.

By Chet Haase

Source https://medium.com/androiddevelopers/navigating-with-deep-links-910a4a6588c

Previous Diamanti Launches Diamanti Ultima To Simplify Data Management In Enterprise Kubernetes
Next Top Cloud Trends For 2021: Forrester Predicts Spike In Cloud-Native Tech, Public Cloud, And More