离线优先的 Trusted Web Activity

Demián Renzulli
Demián Renzulli

当用户首次通过可信 Web 活动启动渐进式 Web 应用 (PWA) 时,由于注册流程尚未完成,因此服务工件尚不可用。此外,如果用户在首次启动应用时没有连接,系统会显示网络错误页面,而不是自定义离线体验。

例如,在用户从 Play 商店下载 PWA 后,就可能会发生这种情况。因此,如果用户在首次尝试打开应用时没有连接到网络,服务工件将无法显示离线后备页面。系统会显示标准错误页面,导致用户体验不佳。

TWA 离线:标准离线网页

本指南介绍了如何在这种情况下,先检查网络状态,然后再启动可信 Web 活动,以显示您自己的 activity。

创建自定义 LauncherActivity

第一步是创建自定义启动器 activity。此 Activity 将包含离线屏幕,用于在用户首次打开应用时显示是否没有连接。

调用 activity OfflineFirstTWALauncherActivity,并使其扩展:com.google.androidbrowserhelper.trusted.LauncherActivity

import com.google.androidbrowserhelper.trusted.LauncherActivity; public class OfflineFirstTWALauncherActivity extends LauncherActivity { } 

接下来,在 AndroidManifest.xml 中注册 activity:

<activity android:name=".OfflineFirstTWALauncherActivity" android:theme="@style/Theme.Design.NoActionBar">  <intent-filter>  <action android:name="android.intent.action.MAIN" />  <category android:name="android.intent.category.LAUNCHER" />  </intent-filter>  <!-- 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.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:host="airhorner.com" android:scheme="https" />  </intent-filter> </activity> 

上述代码会将 OfflineFirstTWALauncherActivity 注册为启动器 activity,并将 https://airhorner.com 定义为 TWA 启动时要打开的网址。

处理离线场景

首先,在 activity 内替换 shouldLaunchImmediately() 方法并使其返回 false,以便 Trusted Web Activity 不会立即启动。您还可以在初始发布之前添加额外的检查:

@Override protected boolean shouldLaunchImmediately() {  // launchImmediately() returns `false` so we can check connection  // and then render a fallback page or launch the Trusted Web Activity with `launchTwa()`.  return false; } 

替换 onCreate() 方法,以便在 TWA 启动之前检查网络状态。添加对 tryLaunchTwa() 的调用,该辅助方法将包含该逻辑:

@Override protected void onCreate(Bundle savedInstanceState) {  super.onCreate(savedInstanceState);  tryLaunchTwa(); } 

接下来,实现 tryLaunchTwa()

private void tryLaunchTwa() {  // If TWA has already launched successfully, launch TWA immediately.  // Otherwise, check connection status. If online, launch the Trusted Web Activity with `launchTwa()`.  // Otherwise, if offline, render the offline fallback screen.  if (hasTwaLaunchedSuccessfully()) {  launchTwa();  } else if (isOnline()) {  firstTimeLaunchTwa();  } else {  renderOfflineFallback();  } } 

上述代码会处理以下三种场景:

  • 如果 TWA 之前已启动,则服务工件已注册,并且 PWA 将能够离线响应。在这种情况下,调用父类中定义的 launchTwa() 即可直接启动 Trusted Web Activity。
  • 如果 TWA 之前未启动且用户处于在线状态,请使用稍后将要实现的 firstTimeLaunchTwa() 方法首次启动可信 Web Activity。
  • 如果 TWA 尚未启动且用户处于离线状态,请呈现原生离线后备页面。

实现辅助方法

最后一步是实现上一部分代码调用的辅助方法。以下是用于检查离线状态 isOnline() 的代码:

private boolean isOnline() {  ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);  NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();  return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } 

接下来,实现 hasTwaLaunchedSuccessfully(),用于检查 TWA 是否至少已启动一次:

private boolean hasTwaLaunchedSuccessfully() {  // Return `true` if the preference "twa_launched_successfully" has already been set.  SharedPreferences sharedPref = getSharedPreferences(getString(R.string.twa_offline_first_preferences_file_key), Context.MODE_PRIVATE);  return sharedPref.getBoolean(getString(R.string.twa_launched_successfully), false); } 

上述代码会从父类调用 launchTWA(),并将 twa_launched_successfully 标志保存在共享偏好设置中。这表示 TWA 至少已成功启动一次。

其余辅助方法 renderOfflineFallback() 会渲染 Android 离线屏幕。

private void renderOfflineFallback() {  setContentView(R.layout.activity_offline_first_twa);  Button retryBtn = this.findViewById(R.id.retry_btn);  retryBtn.setOnClickListener(new View.OnClickListener() {  public void onClick(View v) {  // Check connection status. If online, launch the Trusted Web Activity for the first time.  if (isOnline()) firstTimeLaunchTwa();  }  }); } 

在本演示中,我们定义了 activity_offline_first_twa 布局,其中包含一个用于重试的按钮,该按钮会在检查连接后及时执行 firstTimeLaunchTwa()

twa offline - custom offline screen

总结

  • 当用户首次通过可信 Web 活动启动渐进式 Web 应用 (PWA) 时,Service Worker 尚不可用。
  • 为了避免在用户没有连接的情况下显示标准离线屏幕,您可以检测离线状态,并改为显示回退离线屏幕。
  • 在本指南中,您学习了如何实现该策略。如果您有兴趣查看本指南中使用的代码,可以参阅“离线优先”TWA 演示版,找到完整的解决方案。