5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

TWA(Trusted Web Activity) で任意のページを表示させる

Posted at

はじめに

TWA ではアプリ起動時に表示するページを AndroidManifest.xml に定義します。
まあだいたいトップページを指定していると思います。

ふつーに起動した場合にはソレで問題ないのですが、たとえばプッシュ通知からアプリを起動した場合には別のページ(キャンペーンページとか)を表示したい、なんていう要望が必ず出てきます。

そんなときの対応方法メモです。

TWA の詳しい実装方法などは コチラ がわかりやすいです。

環境

macOS High Sierra - 10.13.6
Android Studio - 3.4

方法

とても簡単です。

LauncherActivity を継承したクラスを作成します

MainActivity.kt
class MainActivity : LauncherActivity() {
}

getLaunchingUrl() をオーバーライドします

MainActivity.kt
class MainActivity : LauncherActivity() {
    override fun getLaunchingUrl(): Uri {
        return super.getLaunchingUrl()
    }
}

intent から URL を受け取れるようにし、URL が渡されていた場合はそちらを return するようにします

MainActivity.kt
class MainActivity : LauncherActivity() {
    companion object {
        val EXTRA_PARAM_URL = "url"
    }

    override fun getLaunchingUrl(): Uri {
        val url = intent.getStringExtra(EXTRA_PARAM_URL)
        if (url != null) {
            return Uri.parse(url)
        }
        return super.getLaunchingUrl()
    }
}

以上で任意のページを表示させる準備が整いました。

あとはプッシュのパラメータから取得した URL を PendingIntent にセットすれば完了です。

MyFirebaseMessagingService.kt
class MyFirebaseMessagingService : FirebaseMessagingService() {
    ...
    override fun onMessageReceived(remoteMessage: RemoteMessage?) {
        if (remoteMessage != null) {
            ...
            val notifyIntent = Intent(context, MainActivity::class.java)
            notifyIntent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
            notifyIntent.putExtras(intent)
                .putExtra(MainActivity.EXTRA_PARAM_URL, [プッシュから取得したURL])
            val requestId = System.currentTimeMillis().toInt()
            val pendingIntent = PendingIntent.getActivity(context, requestId, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT)
            ...
        }
    }
}

参考

【実践】Google Play Store でPWA配信 (TWA)
TWAの挙動をPWAに寄せていく(起動編)

5
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?