在我看来,有一种更简单的方法。
首先:在 AndroidManifest.xml 中声明您的 TWA 活动,如下所示。请注意,默认情况下它不会启动,因为它不处理 android.intent.action.MAIN 意图,因此您可以实现自己的主要活动。
<activity
android:name="com.google.androidbrowserhelper.trusted.LauncherActivity">
<!-- Edit android:value to change the url opened by the TWA -->
<meta-data
android:name="android.support.customtabs.trusted.DEFAULT_URL"
android:value="https://YOUR_SITE_URL" />
<!--
This intent-filter allows the TWA to handle Intents to open
YOUR_SITE_URL
-->
<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="YOUR_SITE_URL"/>
</intent-filter>
</activity>
第二:在您的代码中某处以这样的意图启动 TWA 活动。如果您愿意,您还可以在意图中传递站点 url。
Intent intent = new Intent(this, com.google.androidbrowserhelper.trusted.LauncherActivity.class);
intent.setData(Uri.parse("ANOTHER_SITE_URL"));
startActivity(intent);
还要注意将 TWA 与 AndroidX 一起使用所需的依赖项:
implementation 'androidx.browser:browser:1.0.0'
implementation 'com.github.GoogleChrome:android-browser-helper:ff8dfc4ed3d4133aacc837673c88d090d3628ec8'