background

For Alibaba.com, with the rapid development of ICBU global buying and global selling strategy, the number of users in weak areas is increasing, among which the users in India have surpassed the users in the United States to become the largest source of users on the website. However, these users have poor network, poor model and small memory, so it is expensive for them to download and retain APP. In the spirit of customer first, we need to think about how to enable users to download our APP in the application market and generate continuous conversion, while ensuring a better experience for users when browsing the website.

So here are a few things to consider:

  • The experience is better
  • Native apps are small enough
  • Development and maintenance costs need to be as low as possible

Based on the above points, it seems that the best approach is to encapsulate a PWA-compliant WEB site (good experience) (low development and maintenance costs) into a separate native APP (small size) that can be placed on a shelf.


Results show


What is the PWA

PWA (Progressive Web Apps) refers to the use of modern Web apis and traditional Progressive enhancement strategies to create cross-platform Web applications with the same user experience advantages as native applications.

It mainly includes the following capabilities (how to implement PWA is not the focus of this article, you can refer to the documentation above MDN). :

  • APP shell
  • service worker
  • The web store
  • index DB
  • Add web sites to your desktop
  • Notifications and notifications
  • Offline access

In a word, websites with PWA capability will make users’ browsing experience smoother and more native.


The difference between the WEBVIEW CCTS/TWA

webview

Generally speaking, in the android development, can be very good for web display by means of the webview, but his limitations are also obvious, the webview is not a browser, if we want to realize part of the browser’s ability, we need to independent development in the end, and can’t enjoy the browser upgrade brings us convenience.

CCT (Chrome Custom Tabs)

In order to solve some of the problems mentioned above in WebView, Google launched CCT (Chrome Custom Tabs) technology, which can use the browser features of the user’s mobile phone to render websites in native. One key limitation is that there is an address bar at the top, which makes the experience feel like it’s not native.

TWA (Trusted Web Activities)

In order to solve the CCT problem, Google introduced a new technology system: Trusted Web Activities (TWA), TWA is a new way to integrate Web applications. It can integrate PWA applications with Android Apps using a Custom Tabs protocol. By using Digital AssetLinks to authenticate the website and native to ensure that the developers on both sides are the same, the address bar in CCT can be hidden in this way to make the website more native.

Here’s a look at the differences between the three:


How to implement TWA

From the above we can see that TWA has many advantages. It can not only display website content in full screen, but also share Chrome storage, use the latest Chrome API and do not require native development capabilities. In addition, one of the biggest advantages is that the implementation cost is very low (if the site already supports PWA).

Here’s what you need to do, and I’ll cover it all in this article:

1. Get your PWA icon certified by Lighthouse

2. Initialize the project

3. Establish a trust relationship between the website and TWA (to hide the address bar)

4. Build and sign your APP


Get your PWA icon certified by Lighthouse

You can run Lighthouse in two ways: 1. Run it as a Chrome extension, or 2. Run as a command line tool. The Chrome extension provides a more user-friendly interface for easy reading of reports. The command-line tools allow you to integrate Lighthouse into a continuous integration system. Today we are going to show you how to run the Chrome extension.

  • Download Google Chrome 52 or later.
  • Install the Lighthouse Chrome extension.
  • Click the Lighthouse icon on the Chrome toolbar. (If you don’t see it, it might be hidden in the Main menu of Chrome.)
  • On the page you want to analyze, click the icon and then click the Generate Report button
  • Wait a moment to get a report of the current page

After getting the report, we can see all the points that need to be optimized on the current page, and the corresponding modification plan will have a complete plan in the report. We just need to solve the problem according to the plan.


Initializing the project

New project

When creating Trusted Web Activities, the project must be API 16 or later.

  • Open Android Studio and click the Start a New Android Studio Project option.
  • Android Studio will prompt you to select the Activity type. Since TWA uses the activities provided by the Support library, select Add No Activity and click Next. Here’s a brief description of each field:
  • Name: Indicates the application Name on the Android desktop.
  • Package Name: The unique identifier of the Android application on the Play store and Android devices. Check out the documentation for requirements and best practices for creating package names for Android applications.
  • Save Location: Android Studio will create a directory for the project on your computer.
  • Language: This project does not require writing any Java or Kotlin code. Select Java as the default.
  • Minimum API Level: The support library requires at least API 16. Select a version of API 16 or later.
  • Ignore the other options, and click Finish.


Get the TWA dependency library

To set up the TWA dependent library, you need to edit several files.

First go to build.gradle in the APP directory (Trusted Web Activities library to use Java 8 functionality, first enable Java 8. Add the compileOptions configuration in Android.)


android {
        ...
    compileOptions {
       sourceCompatibility JavaVersion.VERSION_1_8
       targetCompatibility JavaVersion.VERSION_1_8
    }
}Copy the code


Next add the TWA Support library to the project. Add a new dependency to Dependencies:


dependencies {
   implementation 'com.github.GoogleChrome.custom-tabs-client:customtabs:d08e93fce3'
}
Copy the code


Android Studio will ask if you want to synchronize the project. Click Sync Now to synchronize the project.


Start the TWA Activity

Set the TWA Activity by editing the Android App Manifest.

On the Project Navigator, expand the App section, then expand the Manifests and double-click androidmanifest.xml to open the file.

Because we did not add any activities when we created the project, the manifest is empty and contains only the application tag.

Add TWA Activity by inserting the Activity tag in the Application tag:


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.twa.myapplication">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:ignore="GoogleAppIndexingWarning">
        <activity
            android:name="com.google.androidbrowserhelper.trusted.LauncherActivity"> <! -- Edit android:value to change the url opened by the Trusted Web Activity --> <meta-data android:name="android.support.customtabs.trusted.DEFAULT_URL"
               android:value="https://airhorner.com"/ > <! -- This intent-filter adds the Trusted Web Activity to the Android Launcher --> <intent-filter> <action android:name="android.intent.action.MAIN" />
               <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> <! -- This intent-filter allows the Trusted Web Activity to handle Intents to open airhorner.com. --> <intent-filter> <action android:name="android.intent.action.VIEW"/>
               <category android:name="android.intent.category.DEFAULT" />
               <category android:name="android.intent.category.BROWSABLE"/ > <! -- Edit android:host to handle links to the target URL--> <data android:scheme="https"
                 android:host="airhorner.com"/>
           </intent-filter>
        </activity>
    </application>
</manifest>
Copy the code


The markup added to the XML is the standard Android App Manifest. Trusted Web Activities have two related information:

  • meta-dataThe tag tells the TWA activity which URL to open. Modify theandroid:valueThe URL for the PWA page you want to open. The sample forhttps://airhorner.com.
  • In the secondintent-filterThe TAB allows TWA to intercept Android Intents openedhttps://airhorner.com. theandroid:hostInternal propertiesdataThe TAB must point to the URL opened by TWA.


Build trust between website and TWA (hide address bar)

Trusted Web Activities require associations between Android applications and Web sites to remove the URL bar. This association was created through Digital Asset Links and must be linked in two ways: from APP to website and from website to APP. You can also set the APP to website validation and set Chrome to skip the website to APP validation for debugging.


Build connections from APP to website

Open the string resource file app > res > values > strings.xml and add the Digital AssetLinks statement below:


<resources>
    <string name="app_name">AirHorner Trusted Web Activity</string>
    <string name="asset_statements"> [{\"relation\": [\"delegate_permission/common.handle_all_urls\"], \"target\": { \"namespace\": \"web\", \"site\": \"https://airhorner.com\"} }]  Copy the code


Change the contents of the site property to match the Scheme and domain opened by TWA.

Go back to the androidmanifest.xml file and link to the statements by adding a new meta-data tag to the application tag:


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.twa.myapplication">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <meta-data
            android:name="asset_statements"
            android:resource="@string/asset_statements" />

        <activity>
            ...
        </activity>

    </application>
</manifest>Copy the code


We have now established a link from the Android APP to the website. We can debug without creating a website to APP validation. Here’s how to test it on a development device:

Enable debug mode
  1. Open Chrome on your developer device and navigate tochrome://flags, and searches for names on non-root devicesEnable command lineAnd then change it toENABLEDThen restart the browser.
  2. Next, on a terminal, use the Android Debug Bridge (installed with Android Studio) and run the following command:
adb shell "echo '_ --disable-digital-asset-link-verification-for-url=\"https://airhorner.com\"' > /data/local/tmp/chrome-command-line"Copy the code

Close Chrome and restart your application from Android Studio. The application should now be displayed in full screen.


Build connections from websites to apps

The developer needs two pieces of information from the APP to create the association:

  • Package Name:The first piece of information is the package name of the APP. This is the same package name that was generated when the APP was created. Can be found inGradle Scripts > build.gradle (Module: app)Found in theapplicationIdThe value of the.
  • Sha-256 Fingerprint: You must sign the Android application to upload it to the Play Store. The same signature is used to establish a connection between the website and APP via sha-256, which uploads the key.

The Android documentation details how to use Android Studio to generate keys. Make a note of the path, alias, and password of the key, as you will need them in the next step. To extract SHA-256 using keytool, run the following command:


keytool -list -v -keystore  -alias  -storepass  -keypass Copy the code



Sha-256 is printed in the Certificate. Here is a sample output:


keytool -list -v -keystore ./mykeystore.ks -alias test -storepass password -keypass password

Alias name: key0
Creation date: 28 Jan 2019
Entry type: PrivateKeyEntry
Certificate chain length: 1
Certificate[1]:
Owner: CN=Test Test, OU=Test, O=Test, L=London, ST=London, C=GB
Issuer: CN=Test Test, OU=Test, O=Test, L=London, ST=London, C=GB
Serial number: ea67d3d
Valid from: Mon Jan 28 14:58:00 GMT 2019 until: Fri Jan 22 14:58:00 GMT 2044
Certificate fingerprints:
   SHA1: 38:03:D6:95:91:7C:9C:EE:4A:A0:58:43:A7:43:A5:D2:76:52:EF:9B
   SHA256: F5:08:9F:8A:D4:C8:4A:15:6D:0A:B1:3F:61:96:BE:C7:87:8C:DE:05:59:92:B2:A3:2D:05:05:A5:62:A5:2F:34
Signature algorithm name: SHA256withRSA
Subject Public Key Algorithm: 2048-bit RSA key
Version: 3Copy the code

Once you have these two pieces of information, open the AssetLinks generator, fill in the fields, and click Generate Statement. Copy the generated statement and place it in the /.well-known/assetlinks.json directory on your website.


Create icon

When a new project is created in Android Studio, it comes with a default icon. As part of development, you want to use a different icon than other apps. Android Studio has Image Asset Studio, which provides the tools necessary to create an icon that can fit any size and pixel.

Open Android Studio, navigate to File > New > Image Asset, select Launcher Icons (Adaptative and Legacy) and use the prompt to create an appropriate icon for your application.


Add splash screen

In Chrome 75 +, TWA supports adding kinetic energy to the launch animation, which we can do by adding a few images and Settings. (Be sure to use Chrome 75 or later and use the latest TWA dependent library)


Add some images to the startup animation

Android comes in different screen sizes and pixel densities, and to ensure that the boot animation works for all devices, you need to generate images for each pixel density.

Fully explaining support for all pixels is beyond the scope of this article, but an example is to create a 320x320DP image that represents a 2×2-inch square on the screen of any device at any density, equivalent to 320×320 pixels at mdPI density.

From there we can get the size required for other pixel densities. Below is a list of the pixel density, the multiplier applied to the base size (320x320DP), the resulting size in pixels, and where the image should be added to the Android Studio project.


Update some configurations

First, add the Content-provider to AndroidManifest (Androidmanifest.xml)


<application>
    ...
    <provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="com.example.twa.myapplication.fileprovider"
        android:grantUriPermissions="true"
        android:exported="false">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/filepaths" />
    </provider>
</application>Copy the code


Then, add the res/ XML/Filepass.xml resource and make the startup animation with path TWA


<paths>
    <files-path path="twa_splash/" name="twa_splash" />
</paths>Copy the code


Finally, add meta-tags to AndroidManifest (Androidmanifest.xml)


<activity android:name="com.google.androidbrowserhelper.trusted.LauncherActivity">... <meta-data android:name="android.support.customtabs.trusted.SPLASH_IMAGE_DRAWABLE"
               android:resource="@drawable/splash"/>
    <meta-data android:name="android.support.customtabs.trusted.SPLASH_SCREEN_BACKGROUND_COLOR"
               android:resource="@color/colorPrimary"/>
    <meta-data android:name="android.support.customtabs.trusted.SPLASH_SCREEN_FADE_OUT_DURATION"
               android:value="300"/>
    <meta-data android:name="android.support.customtabs.trusted.FILE_PROVIDER_AUTHORITY"
               android:value="com.example.twa.myapplication.fileprovider"/>
    ...
</activity>Copy the code


Make sure the page is transparent at startup

Also, make sure the page is transparent at startup to avoid a white screen before the animation starts.

First, add a new theme in res/styles.xml:


<style name="Theme.LauncherActivity" parent="Theme.AppCompat.NoActionBar">
     <item name="android:windowAnimationStyle">@null</item>
     <item name="android:windowIsTranslucent">true</item>
     <item name="android:windowNoTitle">true</item>
     <item name="android:windowBackground">@android:color/transparent</item>
     <item name="android:backgroundDimEnabled">false</item>
 </style>Copy the code


Then add a reference to the new style in AndroidManifest (Androidmanifest.xml)


<application>
    ...
    <activity android:name="com.google.androidbrowserhelper.trusted.LauncherActivity"
              android:theme="@style/Theme.LauncherActivity">... </activity> </application>Copy the code


Build and sign your APP

Save assetLinks in your website, and once asset_statements have been configured in the Android APP, the next step is to generate the signed APP. Please check the documentation.

APK can be installed into the test device using ADB:


adb install app-release.apkCopy the code


If authentication fails, you can use ADB to view error messages from the connected device and computer terminal.


adb logcat | grep -e OriginVerifier -e digital_asset_linksCopy the code


Bingo, generate upload APK, you can upload the app to the Play store.


conclusion

Alibaba.com’s version of TWA is now available on Amazon Play, and its business value is much higher than existing sites, although it’s still a long way from native apps.

In addition to a point: TWA is never replace the native APP, he must be through the remedy some of the native APP, or to help carry something native APP to serve those who make native APP (low android version, etc.) of users, for any technology, it must be cooperate with each other to achieve business value maximization, is a good technical solution.


PS: TWA refers to the native APP encapsulated by Google TWA technology. Native apps are native apps developed in Java


Refer to the reference

Developers.google.com/web/android…

www.infoq.cn/article/XTE…

Juejin. Cn/post / 684490…