override fun onMessageReceived(pushMessage: RemoteMessage) {
super.onMessageReceived(pushMessage)
val title = pushMessage.notification?.title
val body = pushMessage.notification?.body
val data = pushMessage.data.toBundle()
showNotification(title, body, data)
}
private fun showNotification(title: String?, body: String?, data: Bundle) {
val startAppActivity = packageManager.getLaunchIntentForPackage(packageName)?.apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
putExtras(data)
}
val pendingIntent = PendingIntent.getActivity(
this,
0,
startAppActivity,
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
} else {
PendingIntent.FLAG_UPDATE_CURRENT
}
)
...
val notificationBuilder = NotificationCompat.Builder(
this,
channelId
).apply {
...
setContentIntent(pendingIntent)
}
notificationManager.notify(id, notificationBuilder.build())
}
When app is in foreground and there is a new notification from firebase then the app creates a custom notification but when I click on it on Android 12+ it just returns to the app without recreating launcher activity and onNewIntent is not being called also, the data is lost and not handled.
It works fine for older versions of Android
How to fix it?
UPDATE
Fixed by changing
packageManager.getLaunchIntentForPackage(packageName)
to
Intent(this, MainActivity::class.java)
Now it recreates the activity all the time.
I thought that there was no difference because MainActivity is the launcher activity and I also override flags (flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK) anyway but it seems the intent returned by getLaunchIntentForPackage method contains something else which prevents activity recreation, would be great to have some info how exactly it's different, including different versions of Android