One solution is to store the data in shared preference or sqlite db depending on your requirment, in onMessageReceived, and if you want onMessageRecieved irrespective of app is in foreground or backgroun, then instead of sending notification message too user always send data message to user and show show notification using NotificationBuilder instead of default FCM notification, this way you'll always have data in local persistence.
override fun onMessageReceived(remoteMessage: RemoteMessage) {
val sp = applicationContext.getSharedPreferences("NOTIFICATION_SHARED_PREFERENCE",Context.MODE_PRIVATE)
val editor = sp.edit()
editor.putString("data",remoteMessage.data.toString())
editor.commit()
val pendingIntent:PendingIntent = PendingIntent.getActivity(this,Random().nextInt(),intent,0)
showNotification(remoteMessage.data["title"]!!,remoteMessage.data["body"]!!,pendingIntent)
}
private fun showNotification(title:String,description: String,pendingIntent: PendingIntent){
val icon = R.drawable.ic_notification
val notification = NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(icon)
.setContentTitle(title)
.setContentText(description)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setGroup(GROUP_KEY_PUSH_MESSAGES)
.setContentIntent(pendingIntent)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setAutoCancel(true)
.build()
NotificationManagerCompat.from(applicationContext).apply {
notify(Random().nextInt(),notification)
}
}
and you can access the data directly in fragment using following method, no need to pass data to fragment from activity.
val sp = applicationContext.getSharedPreferences("NOTIFICATION_SHARED_PREFERENCE",Context.MODE_PRIVATE)
val type = object : TypeToken<HashMap<String,String>>() {}.type
val data:HashMap<String,String> = Gson().fromJson(sp.getString("data",""),type)
intent.putExtra("user2",data["user2"])//use the prefered key