I need to start an Activity from a Notification that I am creating in a FirebaseMessagingService. My problem is that I cannot pass custom action and extra to my ResultActivity in that case if ResultActivity is not in the stack and it is firstly created. In this case the ResultActivity get the intent with the android.intent.action.MAIN without the extra. Can somebody help what could be the problem, and how I can pass the notificationId extra to my Activity?
private fun sendNotification(remoteNotification: RemoteMessage.Notification, data: Map<String, String>) {
val notificationManager = NotificationManagerCompat.from(applicationContext)
createNotificationChannel(notificationManager)
val notification = NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_text_info)
.setContentTitle(this.applicationInfo.loadLabel(packageManager).toString())
.setContentText(remoteNotification.body)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setAutoCancel(true)
.setContentIntent(
getNotificationContentItem(
data.getOrDefault(NOTIFICATION_DATA_KEY_NOTIFICATION_ID, NOTIFICATION_DATA_KEY_NOTIFICATION_ID)
)
)
.build()
notificationManager.notify(getRandomNotificationId(), notification)
}
private fun createNotificationChannel(notificationManager: NotificationManagerCompat) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH)
channel.description = CHANNEL_DESCRIPTION
notificationManager.createNotificationChannel(channel)
}
}
private fun getNotificationContentItem(notificationId: String): PendingIntent? {
val notificationIntent = Intent(this, ResultActivity::class.java)
notificationIntent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP
notificationIntent.action = ACTION_START_NOTIFICATION_DETAILS
notificationIntent.putExtra(EXTRA_NAME_NOTIFICATION_ID, notificationId)
var flags = PendingIntent.FLAG_CANCEL_CURRENT
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
flags = flags or PendingIntent.FLAG_IMMUTABLE
}
val builder = TaskStackBuilder.create(this)
val pendingIntent = builder.run {
addNextIntentWithParentStack(notificationIntent)
getPendingIntent(0, flags)
}
return pendingIntent
}