An Android Studio App Links Tutorial

This chapter will provide a practical demonstration of Android app links and the Android Studio App Link Assistant.

This chapter will add app linking support to an existing Android app, allowing an activity to be launched via an app link URL. In addition to launching the activity, the content displayed will be specified within the URL’s path.

About the Example App

The project used in this chapter is named AppLinking and is a basic app designed to allow users to find information about landmarks in London. The app uses a SQLite database accessed through a standard Android content provider class. The app has an existing database containing records for some popular tourist attractions in London. In addition to the existing database entries, the app lets the user add and delete landmark descriptions.

Currently, the app allows the existing records to be searched and new records to be added and deleted.

The project consists of two activities named AppLinkingActivity and LandmarkActivity. AppLinkingActivity is the main activity launched at app startup. This activity allows the user to enter search criteria and add records to the database. When a search locates a matching record, LandmarkActivity launches and displays the information for the related landmark.

 

You are reading a sample chapter from Android Studio Giraffe Essentials – Kotlin Edition.

Buy the full book now in eBook (PDF) or Print format.

The full book contains 94 chapters and over 830 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

This chapter will enhance the app to support app linking so that URLs can be used to display specific landmark records within the app.

The Database Schema

The data for the example app is contained within a file named landmarks.db located in the app -> assets –> databases folder of the project hierarchy. The database contains a single table named locations, the structure of which is outlined in Table 84-1:

Column

Type

Description

_id

String

The primary index, this column contains string values that uniquely identify the landmarks in the database.

title

String

The name of the landmark (e.g., London Bridge).

description

String

A description of the landmark.

personal

Boolean

Indicates whether the record is personal or public. This value is set to true for all records added by the user. Existing records provided with the database are set to false.

Table 84-1

Loading and Running the Project

The project is contained within the AppLinking folder of the sample source code download archive located at the following URL:

https://www.ebookfrenzy.com/web/giraffekotlin/index.php

Having located the folder, open it within Android Studio and run the app on a device or emulator. Once the app is launched, the screen illustrated in Figure 84-1 below will appear:

 

You are reading a sample chapter from Android Studio Giraffe Essentials – Kotlin Edition.

Buy the full book now in eBook (PDF) or Print format.

The full book contains 94 chapters and over 830 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

Figure 84-1

As currently implemented, landmarks are located using the ID for the location. The default database configuration currently contains two records referenced by the IDs “londonbridge” and “toweroflondon”. Test the search feature by entering londonbridge into the ID field and clicking the Find button. When a matching record is found, the second activity (LandmarkActivity) is launched and passed information about the record to be displayed. This information takes the form of extra data added to the Intent object. LandmarkActivity uses this information to extract the record from the database and display it to the user using the screen shown in Figure 84-2.

Figure 84-2

Adding the URL Mapping

Now that the app has been loaded into Android Studio and tested, we can add app link support. The objective is for the LandmarkActivity screen to launch and display information in response to an app link click. This is achieved by mapping a URL to LandmarkActivity. For this example, the format of the URL will be as follows:

http://<website domain>/landmarks/<landmarkId>Code language: plaintext (plaintext)

When all of the steps have been completed, the following URL should, for example, cause the app to display information about the Tower of London:

http://www.yourdomain.com/landmarks/toweroflondonCode language: plaintext (plaintext)

To add a URL mapping to the project, begin by opening the App Links Assistant using the Tools -> App Links Assistant menu option. Once open, the assistant should appear as shown in Figure 84-3:

Figure 84-3

Next, click the Create Applink button to display the panel shown below:

 

You are reading a sample chapter from Android Studio Giraffe Essentials – Kotlin Edition.

Buy the full book now in eBook (PDF) or Print format.

The full book contains 94 chapters and over 830 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

Figure 84-4

Click on the Open URL Mapping Editor button to map a URL to an activity. Within the mapping screen, click on the ‘+’ button (highlighted in Figure 84-5) to add a new URL:

Figure 84-5

In the Host field of the Add URL Mapping dialog, enter either the URL for your own website. If you do not have a website to use for this tutorial, you can still follow most of this chapter using http://www.example.com, though it will not be possible to test features that require the presence of a Digital Asset Links file.

The Path field (marked B in Figure 84-6 below) is where the path component of the URL is declared. The path must be prefixed with / so enter /landmarks into this field.

The Path menu (B) provides the following three path-matching options:

  • path – The URL must match the path component of the URL exactly to launch the activity. For example, if the path is set to /landmarks, http://www.example.com/landmarks will be considered a match. A URL of http:// www.example.com/landmarks/londonbridge, however, will not be considered a match.
  • pathPrefix – The specified path is only considered as the prefix. Additional path components may be included after the /landmarks component (for example, http://www.example.com/landmarks/londonbridge will still be considered a match).
  • pathPattern – Allows the path to be specified using pattern matching in the form of basic regular expressions and wildcards, for example, landmarks/*/[l-L]ondon/*

Since the path in this example is a prefix to the landmark ID component, select the pathPrefix menu option.

 

You are reading a sample chapter from Android Studio Giraffe Essentials – Kotlin Edition.

Buy the full book now in eBook (PDF) or Print format.

The full book contains 94 chapters and over 830 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

Finally, use the Activity menu (C) to select LandmarkActivity as the activity to be launched in response to the app link:

Figure 84-6

After completing the settings in the dialog, click the OK button to commit the changes. Check that the URL is correctly formatted and assigned to the appropriate activity by entering the following URL into the Check URL Mapping field of the mapping screen (where <your domain> is set to the domain specified in the Host field above) :

http://<your domain>/landmarks/toweroflondonCode language: plaintext (plaintext)

If the mapping is configured correctly, LandmarkActivity will be listed as the mapped activity:

Figure 84-7

The latest version of Android requires that App Links be declared for HTTP and HTTPS protocols, even if only one is being used. Therefore, before proceeding to the next step, repeat the above steps to add the HTTPS version of the URL to the list.

The next step will also be performed in the URL mapping screen of the App Links Assistant, so leave the screen selected.

 

You are reading a sample chapter from Android Studio Giraffe Essentials – Kotlin Edition.

Buy the full book now in eBook (PDF) or Print format.

The full book contains 94 chapters and over 830 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

Adding the Intent Filter

As explained in the previous chapter, an intent filter is needed to launch the target activity in response to an app link click. In fact, when the URL mapping was added, the intent filter was automatically added to the project manifest file. With the URL mapping selected in the App Links Assistant URL mapping list, scroll down the screen until the intent filter Preview section comes into view. The preview should contain the modified AndroidManifest.xml file with the newly added intent filters included:

Figure 84-8

Although App Links Assistant has added intent filters for us, it may not have included the autoVerify setting needed when working with app links. Open the manifests -> AndroidManifest.xml file and add this setting to the two intent filters as follows:

<intent-filter android:autoVerify="true">
.
.
    <data
        android:scheme="http"
        android:host="www.ebookfrenzy.com"
        android:pathPrefix="/landmarks" />
</intent-filter>
<intent-filter android:autoVerify="true">
.
.
    <data
        android:scheme="https"
        android:host="www.ebookfrenzy.com"
        android:pathPrefix="/landmarks" />Code language: Kotlin (kotlin)

Adding Intent Handling Code

The steps taken so far ensure that the correct activity is launched in response to an appropriately formatted app link URL. The next step is to handle the intent within the LandmarkActivity class so that the correct record is extracted from the database and displayed to the user. Before making any changes to the code within the LandmarkActivity.kt file, it is worthwhile reviewing some areas of the existing code. Open the LandmarkActivity.kt file in the code editor and locate the onCreate() and handleIntent() methods which should currently read as follows:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityLandmarkBinding.inflate(layoutInflater)
    setContentView(binding.root) 
 
    handleIntent(intent)
}
 
private fun handleIntent(intent: Intent) {
 
    val landmarkId = intent.getStringExtra(AppLinkingActivity.LANDMARK_ID)
 
    landmarkId?.let {
        displayLandmark(it)
    }
}Code language: Kotlin (kotlin)

In its current form, the code expects to find the landmark ID within the extra data of the Intent bundle. Since the activity can now be launched by an app link, this code must be changed to handle both scenarios. Begin by deleting the call to handleIntent() in the onCreate() method:

override fun onCreate(savedInstanceState: Bundle?) {
.
.
    handleIntent(intent)
}Code language: Kotlin (kotlin)

To add the initial app link intent handling code, return to the App Links Assistant panel and click on the Select Activity button listed under step 2. Within the activity selection dialog, select the LandmarkActivity entry before clicking on the Insert Code button:

 

You are reading a sample chapter from Android Studio Giraffe Essentials – Kotlin Edition.

Buy the full book now in eBook (PDF) or Print format.

The full book contains 94 chapters and over 830 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

Figure 84-9

Return to the LandmarkActivity.kt file and note that the following code has been inserted into the onCreate() method (note that you can manually add this code if Android Studio is unable to complete the request):

// ATTENTION: This was auto-generated to handle app links.
val appLinkIntent: Intent = intent
val appLinkAction: String? = appLinkIntent.action
val appLinkData: Uri? = appLinkIntent.dataCode language: Kotlin (kotlin)

This code accesses the Intent object and extracts the Action string and Uri. If the activity launch results from an app link, the action string will be set to android.intent.action.VIEW, which matches the action declared in the intent filter added to the manifest file. If, on the other hand, the activity was launched by the standard intent launching code in the findLandmark() method of the main activity, the action string will be null. By checking the value assigned to the action string, code can be written to identify how the activity was launched and take appropriate action:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityLandmarkBinding.inflate(layoutInflater)
    setContentView(binding.root) 
 
    // ATTENTION: This was auto-generated to handle app links.
    val appLinkIntent: Intent = intent
    val appLinkAction: String? = appLinkIntent.action
    val appLinkData: Uri? = appLinkIntent.data
 
    val landmarkId = appLinkData?.lastPathSegment
 
    if (landmarkId != null) {
        displayLandmark(landmarkId)
    }
}Code language: Kotlin (kotlin)

All that remains is to add some additional code to the method to identify the last component in the app link URL path and to use that as the landmark ID when querying the database:

override fun onCreate(savedInstanceState: Bundle?) {
.
.
    // ATTENTION: This was auto-generated to handle app links.
    val appLinkIntent = intent
    val appLinkAction = appLinkIntent.action
    val appLinkData = appLinkIntent.data
 
    if (appLinkAction != null) {
 
        if (appLinkAction == "android.intent.action.VIEW") {
 
            val landmarkId = appLinkData?.lastPathSegment
 
            if (landmarkId != null) {
                displayLandmark(landmarkId)
            }
        }
    } else {
        handleIntent(appLinkIntent)
    }
}Code language: Kotlin (kotlin)

If the action string is not null, a check is made to verify that it is set to android.intent.action.VIEW before extracting the last component of the Uri path. This component is then used as the landmark ID when making the database query. If, on the other hand, the action string is null, the existing handleIntent() method is called to extract the ID from the intent data.

Testing the App

Run the app on a device or emulator and make sure it is still possible to search for the example landmarks. We have now successfully added app link support to the app. If you specified your own website URL for the app links, we can now take the example one step further by creating and installing a Digital Asset Links file.

 

You are reading a sample chapter from Android Studio Giraffe Essentials – Kotlin Edition.

Buy the full book now in eBook (PDF) or Print format.

The full book contains 94 chapters and over 830 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

Creating the Digital Asset Links File

As outlined in the chapter entitled An Android Intents Overview, to fully support app links, we need to install a Digital Asset Links file on the website referenced in the app link. Begin by following the steps outlined in An Android Intents Overview to locate your debug.keystore file and identify your SHA256 fingerprint.

Next, open the following page in a web browser:

https://developers.google.com/digital-asset-links/tools/generator

Once the page has loaded, enter your website URL into the Hosting site domain field, com.ebookfrenzy.applinking as the App package name, and your SHA256 fingerprint into the App package fingerprint (SHA256) field:

Figure 84-10

Click the Generate statement button to display the generated statement and place it in a file named assetlinks.json in a folder named .well-known on your web server. Return to the generator page and click on the Test statement button to verify that the file is in the correct location. On a successful test, output similar to the following will appear:

 

You are reading a sample chapter from Android Studio Giraffe Essentials – Kotlin Edition.

Buy the full book now in eBook (PDF) or Print format.

The full book contains 94 chapters and over 830 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

Figure 84-11

Assuming a successful test, we are now ready to try out the app link.

Testing the App Link

Test that the intent handling works by returning to the App Links Assistant panel and clicking on the Test App Links button. When prompted for a URL to test, enter the URL (using the domain referenced in the app link mapping) for the londonbridge landmark ID before clicking on the Run Test button:

Figure 84-12

Once the button has been clicked, the Landmark activity should launch on the device or emulator and display information about London Bridge.

Summary

This chapter has demonstrated the steps for implementing App Link support within an Android app project, including using the App Link Assistant in Android Studio, App Link URL mapping, intent filters, handling website association using Digital Asset Links file entries, and App Link testing.