I have an Android application which will receive push notification. The notification have wearable support hence the notification will also be visible in Android wear with action button.
I am looking to pass data when the notification reaches onMessageReceived in FirebaseMessagingService class. Tried setting data in Intent and passed that with Pending Intent.
val intent = Intent(this, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
intent.data = Uri.parse("12345")
intent.putExtra("user_id", "USER ID")
intent.putExtra("date", "DATE")
val pendingIntent = PendingIntent.getActivity(
applicationContext,
System.currentTimeMillis().toInt() , intent,
0
)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationChannel =
NotificationChannel(CHANNEL_ID,
CHANNEL_NAME,
CHANNEL_IMPORTANCE)
val notificationManager =
this.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(notificationChannel)
val notificationBuilder = NotificationCompat.Builder(this,CHANNEL_ID)
.setContentTitle(getString(R.string.app_name))
.setContentText(body)
.setAutoCancel(true)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent)
.extend(NotificationCompat.WearableExtender()
.addAction(NotificationCompat.Action(R.drawable.icon,
"Explore",
pendingIntent))
)
notificationManager.notify(0, notificationBuilder.build())
}
When click on the notification from Wear, capturing the intent in onNewIntent to get the data passed. But couldn't find the data which were passed.
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
setIntent(intent)
// intent.getStringExtra("date")
// intent.extras.getString("date")
// intent.extras.get("date")
// intent.data
}
Couldn't get the data. Is there any way to get the intent passed with the pending intent ? Or how to get the values passed with Pending Intent.
My assumption is that
onNewIntent()is not being called.If you specify
FLAG_ACTIVITY_CLEAR_TOPand your app is already running and there is an instance ofMainActivityin the task stack, Android will remove the existing instance ofMainActivityand create a new one. TheIntentwith "extras" will then be delivered inonCreate()andonNewIntent()will not be called.If your app is not running, tapping the notification will start your app and create a new instance of
MainActivityand theIntentwith the "extras" will be delived inonCreate()andonNewIntent()will not be called.Also, since the
Intentthat you put in thePendingIntentwill be used by Android to launch anActivityfrom a non-Activitycontext, you need to specifyIntent.FLAG_ACTIVITY_NEW_TASK.Also, you should always specify
FLAG_UPDATE_CURRENTwhen getting aPendingIntentwith "extras", because if you do not, you may get an existingPendingIntentwith some old "extras" or maybe none at all. UsingFLAG_UPDATE_CURRENTwill ensure that yourIntent"extras" are copied into thePendingIntenteven if it already exists. Like this: