はじめに
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)
...
}
}
}