Trusted Web Activities are a new way to integrate your web content into your Android app, using a full-screen Chrome Activity.

How do Trusted Web Activities Work?

A Trusted Web Activity runs Chrome, in full screen, inside an Android application, without any browser UI visible.

This a powerful capability and is only allowed when the site being opened and the Android application belong to the same developer. This validation is achieved through Digital AssetLinks.

What you will build

In this codelab, you are going to use an existing Progressive Web App, https://airhorner.com/, and create an Android Application that opens it inside a Trusted Web Activity.

What you'll learn

What you'll need

This codelab is focused on building a Trusted Web Activity. Even though developers won't be required to write any code, some concepts relative to writing Android apps or Progressive apps may be glossed over.

Install Android Studio

Click the link below, and follow the instructions on the Android Studio download page, if you don't already have Android Studio installed in your computer.

Download and Install Android Studio

Download the Code

Click the following link to download all the code for this codelab, and unzip the contents into the folder you want to contain your project:

Download source code for the SVGOMG sample

Alternaternatively, clone the Github Repository:

git clone https://github.com/GoogleChromeLabs/svgomg-twa.git my-sample-twa

Opening the app in Android Studio

Using the shortcut created by the Android Studio installation, start the IDE. The initial screen will look like the screenshot below:

Since we are going to use an existing project as the base for our Trusted Web Activity, select Open an existing Android Studio project, choose the folder containing the source code downloaded on the previous step and click open it.

Modifying the build file to open a different PWA

With the project open, all the configurations we need to change to make it open a different PWA are in a single file: build.gradle.

The gradle file has many configurations, which tells how the Android application is built, including which support libraries to use and Android versions that are supported by the app.

We are going to modify sections of this file that will change the configuration of which PWA will be opened. Here's how the relevant section of the file looks like:

defaultConfig {
    applicationId "org.chromium.twa.svgomg"
    minSdkVersion 16
    targetSdkVersion 28
    versionCode 3
    versionName "1.1.1"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    manifestPlaceholders = [
            hostName: "svgomg.firebaseapp.com",
            defaultUrl: "https://svgomg.firebaseapp.com",
            launcherName: "SVGOMG TWA",
            assetStatements: '[{ "relation": ' +
                    '["delegate_permission/common.handle_all_urls"], ' +
                    '"target": {"namespace": "web", "site": '+
                    '"https://svgomg.firebaseapp.com"}}]'
    ]
    resValue "color", "colorPrimary", "#303F9F"
}

We are going to change our Trusted Web Activity to open https://airhorner.com/. Those are the fields that we are going to change to achieve this:

applicationId

The applicationId uniquely identifies applications on Android devices and on the Google Play store, and follows the same conventions as Java package names, and we need to assign a new one to our application, in order to avoid conflict with applications that may already exist on the device.

For the context of this codelab, we are going to use com.example.mysampletwa as the ID for the application.

defaultConfig {
    applicationId "com.example.mysampletwa"
    ...

hostName

Setting up the correct hostName will allow the Trusted Web Activity to handle links from other applications to the Progressive Web App.

The value must match the domain where the PWA is hosted. In our example: airhorner.com

...
hostName: "airhorner.com",
...

defaultUrl

The defaultUrl controls which URL will be opened when the Trusted Web Activity is started. It is possible to append query parameters to the URL, for the purpose of tracking or passing more information to the PWA. We are going to use twa-codelab=1, to identify the traffic source:

...
defaultUrl: "https://airhorner.com/?twa-codelab=1",
...

launcherName

The launcherName setting is used to set the name the application will have on the Android Launcher. We are going to use AirHorner.

...
launcherName: "AirHorner"
...

assetStatements

Digital Asset Links requires setting up an ownership validation from the Android application to the site, and vice versa.

The assetStatements parameter is used to setup the validation from the Android app to the site and most is boilerplate that defines the relationship. The part we need to change in order to validate a new application is the origin for the site being validated:

...
assetStatements: '[{ "relation": ' +
        '["delegate_permission/common.handle_all_urls"], ' +
        '"target": {"namespace": "web", "site": '+
        '"https://airhorner.com"}}]'
...

The toolbar color

The last parameter in build file, resValue, is used to create an attribute called primaryColor, which is of the type color. The value for this attribute must be a colour using the hexadecimal format, and it defines the colour of the status bar when the Trusted Activity is open.

This is analog of the theme_color defined in the Web Manifest, and we can use the same value that is used there. In the case of AirHorner, the color is defined as #2196F3:

resValue "color", "colorPrimary", "#2166F3"

Summing it up!

Putting it all together, the relevant section of the build.gradle file should looks like the following:

defaultConfig {
    applicationId "com.example.mysampletwa"
    minSdkVersion 16
    targetSdkVersion 28
    versionCode 3
    versionName "1.1.1"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    manifestPlaceholders = [
            hostName: "airhorner.com",
            defaultUrl: "https://airhorner.com/?twa-codelab=1",
            launcherName: "AirHorner",
            assetStatements: '[{ "relation": ' +
                    '["delegate_permission/common.handle_all_urls"], ' +
                    '"target": {"namespace": "web", "site": '+
                    '"https://airhorner.com"}}]'
    ]
    resValue "color", "colorPrimary", "#2166F3"
}

Running the application

We are now ready to run the application on a device. Make sure that you have an Android device or emulator with Chrome 72 or above installed.

Ensure that the gradle file is synchronized and hit the button on the Android Studio toolbar or use the Ctrl+R keyboard shortcut to run the Application.

Android Studio will ask which device to run the application on. Select the connected device or emulator and click OK.

The application is still showing the URL bar on the top. This is expected at this point, and the reason for this is that Digital AssetLinks requires a 2-way validation, and we have only implemented the validation from the Android Application to the site at this point.

On the next section, you are going to learn how to run the Trusted Web Activity in debug mode, so we can test the Android application before setting up Digital Asset Links on our domain.

In order to enable opening the Trusted Web Activity in full screen, the second part of the Digital AssetLinks validation, from the site to the Android application must be enabled.

Enabling debug-mode Trusted Web Activities

When developing a Trusted Web Activity, it is useful to enable a debug mode in Chrome, that enables it to skip the Digital AssetLinks validation from the site to the application.

This comes in handy when experimenting with AirHorner, as we don't own the domain and will be unable to deploy the necessary files to make the validation.

Enable debugging for in chrome://flags

The first step to enable debugging is use Chrome to navigate to chrome://flags on the Android device. Search for the item "Enable command line on non-rooted devices", and change the value to "Enabled" and relaunch Chrome.

Choosing which domain to debug

The flag enabled on the previous step requires us to tell Chrome which domain is going to be debugged.

The SVGOMG sample contains a command-line tool that can help developers to create the required configuration. On the directory where the source-code for the codelab has been downloaded, run:

adb shell "echo '_ --disable-digital-asset-link-verification-for-url=\"https://airhorner.com\"' > /data/local/tmp/chrome-command-line"

Run the application again. This time, the URL bar at the top should have disappeared, and the UI will look like the following:

The warning at the bottom of the screen reminds is that we are using Chrome with a debug parameter enabled.

Congratulations!!

You have created an Android application that opens a Trusted Web Activity! On the next section, you are going to learn how to prepare the site opening to Trusted Web Activity to open it in fullscreen in production.

Enabling Digital AssetLinks on a site

Using the debug mode allows developers know if the Android application is setup correctly. In order to use Trusted Web Activities in production, a full validation needs to be implemented.

It won't be possible to implement this step in the sample, as we don't have access to add files to airhorner.com.

The next section explains how you can implement this validation with your own Progressive Web App.

Collecting the information

Being able to deploy a file on the domain being validated is the first requirement to implementing the validation, and the domain name is the first information we need..

The second information we need is the applicationId. This the ID that uniquely identifies an application on an Android device or on the Google Play Store, and we have created one when modifying the original demo application.

The last information we need the signing key that is going to be used to deploy the Android application to production and the SHA-256 Fingerprint associated to it.

With the path to the signing key, and it's password, here's how to extract the Fingerprint:

> keytool -list -v \
    -keystore ~/.android/debug.keystore \
    -alias androiddebugkey \
    -keypass android \
    -storepass android | grep SHA256

>     SHA256: BD:92:64:B0:1A:B9:08:08:FC:FE:7F:94:B2...

The information we require is the sequence of hexadecimal bytes after the SHA-256 tag.

Adding the validation file to a site

In order to enable the validation on site, a JSON file describing the relationship to the Android application must be hosted at ./.well-known/assetlinks.json.

A tool for generating the contents of this file is available on the Google Developers.

Add the information collected on the previous steps to each respective field. The tool will generate the JSON content, similar to the following:

[{
  "relation": ["delegate_permission/common.handle_all_urls"],
  "target" : { "namespace": "android_app", "package_name": "com.example.app",
               "sha256_cert_fingerprints": ["BD:92:64:B0:1A:B9:08:08:FC:FE:7F:94:B2:F8:4D:E3:E5:15:BF:C2:FA:0B:73:B8:5C:88:E0:B7:60:8C:6F:B3"] }
}]

Add the content generated by the tool to a file and serve it from ./.well-known/assetlinks.json, relative to the root of your domain.

With that step complete, your application show be to open a Trusted Web Activity in fullscreen, without having to enable the debug mode!

Generate an Icon for your Application

When implementing the Trusted Web Activity, we didn't update the icon for the application. Android Studio provides a tool, that helps developers to generate a compatible icon from an existing image. Check the documentation for the Image Asset Studio to create your own icon.

Check your Progressive Web App

When opening a Progressive Web App inside a Trusted Web Activity, the PWA must fulfill the criteria for installability and performance, and have a minimum performance of 80, as measured by Lighthouse.

If your site is not yet a PWA or doesn't meet the criteria, make sure to check the online resources for creating great Progressive Web Apps.