오프라인 우선의 신뢰할 수 있는 웹 활동

Demián Renzulli
Demián Renzulli

사용자가 신뢰할 수 있는 웹 활동을 통해 프로그레시브 웹 앱 (PWA)을 처음으로 실행할 때는 등록 프로세스가 아직 진행되지 않았으므로 서비스 워커를 사용할 수 없습니다. 또한 사용자가 앱을 처음 실행할 때 인터넷에 연결되어 있지 않으면 맞춤 오프라인 환경 대신 네트워크 오류 페이지가 표시됩니다.

이 시나리오의 예는 사용자가 Play 스토어에서 PWA를 다운로드한 후 발생할 수 있습니다. 따라서 사용자가 앱을 처음 열려고 할 때 연결되지 않으면 서비스 워커에서 아직 오프라인 대체 페이지를 표시할 수 없습니다. 표준 오류 페이지가 표시되어 부정적인 경험을 할 수 있습니다.

TWA 오프라인: 표준 오프라인 페이지

이 가이드에서는 신뢰할 수 있는 웹 활동을 시작하기 전에 네트워크 상태를 확인하여 이러한 상황에서 자체 활동을 표시하는 방법을 설명합니다.

맞춤 LauncherActivity 만들기

첫 번째 단계는 맞춤 런처 활동을 만드는 것입니다. 이 Activity에는 사용자가 앱을 처음 열 때 연결이 끊긴 경우 표시되는 오프라인 화면이 포함됩니다.

활동 OfflineFirstTWALauncherActivity를 호출하고 com.google.androidbrowserhelper.trusted.LauncherActivity를 확장합니다.

import com.google.androidbrowserhelper.trusted.LauncherActivity;

public class OfflineFirstTWALauncherActivity extends LauncherActivity {

}

이제 AndroidManifest.xml에 활동을 등록합니다.

<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를 런처 활동으로 등록하고 TWA가 실행될 때 열리는 URL로 https://airhorner.com을 정의합니다.

오프라인 시나리오 처리

먼저 활동 내에서 shouldLaunchImmediately() 메서드를 재정의하고 이 메서드가 false를 반환하도록 하여 신뢰할 수 있는 웹 활동이 즉시 실행되지 않도록 합니다. 최초 실행 전에 추가 검사를 추가할 수도 있습니다.

@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()를 호출하여 신뢰할 수 있는 웹 활동을 직접 시작하세요.
  • TWA가 이전에 실행되지 않았고 사용자가 온라인 상태라면 나중에 구현할 firstTimeLaunchTwa() 메서드를 사용하여 신뢰할 수 있는 웹 활동을 처음으로 실행합니다.
  • TWA가 아직 실행되지 않았고 사용자가 오프라인 상태인 경우 네이티브 오프라인 대체 화면을 렌더링합니다.

도우미 메서드 구현

마지막 단계는 이전 코드에서 호출한 도우미 메서드를 구현하는 것입니다. 다음은 오프라인 상태 isOnline()를 확인하는 코드입니다.

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

그런 다음 TWA가 한 번 이상 실행되었는지 확인하는 hasTwaLaunchedSuccessfully()를 구현합니다.

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 오프라인 - 맞춤 오프라인 화면

결론

  • 사용자가 신뢰할 수 있는 웹 활동을 통해 프로그레시브 웹 앱 (PWA)을 처음 실행할 때는 서비스 워커를 아직 사용할 수 없습니다.
  • 사용자가 인터넷에 연결되어 있지 않을 때 표준 오프라인 화면이 표시되지 않도록 하려면 오프라인 조건을 감지하고 대신 대체 오프라인 화면을 표시하면 됩니다.
  • 이 가이드에서는 이 전략을 구현하는 방법을 배웠습니다. 이 가이드 전체에서 사용한 코드를 확인하고 싶다면 오프라인 첫 TWA 데모에서 전체 솔루션을 확인하세요.