Deep Linking in Android

In today’s blog post, we will learn about Deep linking in Android and what are its Benefits?

Before, we jump to the code let’s first understand:

What is Deep Linking?

Deep linking can be defined as a concept where a custom link, which when clicked, will navigate the user to some specific content inside the application rather than displaying it on the website.

Why we need Deep Linking?

You can navigate the user directly to the specific page of the application and show them specific content, they are interested in. Let’s explain this more with an example:

Suppose a user who has installed your application but hasn’t used it in a long time, chances are that the user might uninstall it, to free up the phone’s memory. Think of the business which had to spend millions of dollars to build that application as part of their App first policy!

However, you can change all this with an SMS or an email or a simple push notification and pull him to a specific deal/offer/product in which the user might be interested in, with much thanks to Deep Linking functionality in the Application!!

Let’s take another example, you have a simple application where the user registers for a new account, and thus an activation email is sent to the user to validate and activate his account.

At this time, you are letting the user leave your application and go to some other 3rd party application to check his email, a highly risky affair.

Now, When the user taps on the activation link and thus verifying his account, the application is launched and based on application logic he might be directed to login/dashboard page.

Have you ever thought, how this happened? Deep linking to the rescue again!

Last but not the least, think of Deep Linking as a tool that can we used to take a user to different campaigns which in turn can strengthen the marketing/revenue for the product.

Think of a product let’s say a Travel Booking App which has just started a sale on booking a trip to London. The Audiences, which loves to travel, can be targeted with deep links embedded with the mentioned offer to lure them for booking their trips by landing them on the page, inside the application, with the sale filter already selected.

This also helps to track which campaigns are actually working and helps in planning better.

How to Implement Deep Linking?

Deep linking in Android is a very straight forward implementation, before we jump into that, let’s have a look at the Deep Link Url format:

http://www.androidinformative.com/Aboutme

The above Url, can be broken into following components:

  1. Scheme – http
  2. Host– www.androidinformative.com
  3. Path Prefix(not mandatory) – Aboutme

Let’s have a look at another Deep Link format, which we will be using in our sample application:

deeplinksample://dashboard

  1. Scheme – deeplinksample
  2. Host – dashboard

Let’s see how to implement this in the project:

Go to your Manifest file and declare the Intent filter which will listen to the Deep Links

    <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.BROWSABLE" />
                <category android:name="android.intent.category.DEFAULT" />
                <data
                    android:host="dashboard"
                    android:scheme="sarabdeeplinksample" />
            </intent-filter>

Let’s explain one by one the usage of each one-by-one

Intent action(VIEW) – We use it so that the intent filter can be reached via search console like google, etc.

Category(BROWSABLE) – We use this flag so that the intent filter is accessible from the web browser.

Category(DEFAULT) – We use this flag so that our application can respond to implicit intents

Data – This is where the core of the deep linking sits. Each data tag corresponds to a URI format that represents each activity inside your application

Now, Create a Deep Link Activity which will be launched every-time user clicks on a deep link so that the application can take appropriate action

  /**
     * Deep Link Manager will handle the deep link and then we will quit our DeepLinkHandling
     * activity as it has performed its task successfully
     */
override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mDeepLinkManager = DeepLinkManager()

        intent?.run {
            handleDeepLink()
            finish()
        }
        finish()
    }
 /**
     * Deep Link Manager takes the appropriate action
     */
 private fun handleDeepLink() {
        mDeepLinkManager.resolveLink(this, intent)
    }

Let’s take a look at the enum which corresponds to the deep links that our app supports:

/**
 * Enums that corresponds to the Supported DeepLinks
 */
enum class DeepLinks(val mScheme: Int, val mHost: Int) {
    DASHBOARD(R.string.deep_link_scheme, R.string.deep_link_host_dashboard);
}

Now, let’s have a look at the Deep Link Manager:

 /**
     * Iterate over the application supported DeepLinks and return the matched deepLink
     */
    private fun checkAndGetDeepLink(context: Context, intent: Intent): DeepLinks? {
        val deepLinks = DeepLinks.values()
        for (link in deepLinks) {
            if (intent.data.toString().contains(
                    getAppSupportedDeepLinkString(
                        context.getString(link.mScheme),
                        context.getString(link.mHost)
                    )
                )
            ) {
                return link
            }
        }
        return null
    }

    /**
     * Resolve the deep link for appropriate action
     */
    fun resolveLink(context: Context, intent: Intent) {
        intent.let {
            val appDeepLink = checkAndGetDeepLink(context, it)
            navigate(context, appDeepLink, it)
        }
    }


    /**
     * Navigate the user to the directed Screen
     */
    private fun navigate(
        context: Context,
        appDeepLink: DeepLinks?,
        deepLinkIntent: Intent
    ) {
        val intent = getDeepLinkIntent(context, appDeepLink)
        intent?.run {
            intent.data = deepLinkIntent.data
            context.startActivity(intent)
        }
    }

    /**
     * This  method will check and return the entry point of the deeplink
     */
    private fun getDeepLinkIntent(
        context: Context,
        appDeepLink: DeepLinks?
    ): Intent? {
        return appDeepLink?.run {
            if (appDeepLink == DeepLinks.DASHBOARD) {
                return Intent(context, DashboardActivity::class.java)
            }
            return null
        }
    }

Now the question comes, how to test the deep linking explained above?

Well, you can do it by using ADB by following these steps:

  1. Download the source code from here
  2. Install the application on your device
  3. Open Application and put it in background
  4. Run the following command in your terminal:
  5. adb shell am start  -W -a android.intent.action.VIEW -d  sarabdeeplinksample://dashboard sarabjit.blog.deeplinkingsample 
  6. Bingo! You will see the Dashboard Activity which gets triggered from the deep link

For some use-cases, you might wish to pass parameters when a deep link is triggered which can be done in the following ways through ADB

adb shell am start  -W -a android.intent.action.VIEW -d  sarabdeeplinksample://dashboard –ez “isRegistered” “true” sarabjit.blog.deeplinkingsample 

Always remember the data is passed in the form of key-value pair. In the above command, ez stands for a boolean type. For other types, please refer to this page:

https://developer.android.com/studio/command-line/adb#IntentSpec

In summary, we just created our first basic deep link application. However, remember with Deep links, if there exists another app that can handle the same type of Intent filter which your application handles, it would pop up in the selection dialog which might cause security issues especially if you are working on a banking sector App.

To overcome this, Android introduced Android App Links(on Android 6) where your application can declare itself as the owner of the link being clicked by the user, hence no more selection dialogs!

We will talk about this in the coming blog posts. One more thing which is worth mentioning here is that the deep links which we talked about in this blog post will work only when the application is installed.

However, if the application does not exist on the device where the link is being triggered, nothing will happen.

Ideally, the user should be directed to the Playstore to download the application and once installed, trigger the very same deep link which the user clicked! This is achievable using Deferred Deep Linking.

We will cover that in our coming blog post, stay tuned and happy coding!