Reputation: 3592
I am working with Android TaskStackBuilder for creating notifications with predefined stack when notification is clicked.
In the app I have 2 activities:
In main activity I show notification with a TaskStackBuilder and the following stack: [MainActivity(launcher intent), ActivityB]
When notification shows I pull down the status bar and click on the notification, I then see ActivityB as expected and when click on back button I then see MainActivity as expected as well, but its onCreate is called!! Is there explanation for this? This actually means that the MainActivity has completely restarted! Why?
MainActivity launchMode:"singleTop"
In addition, it seems that a new MainActivity is created once notification is clicked instead restore the original MainActivity which was already opened. (hash is different, original MainActivity onDestroy is called!)
The notification pending intent created like this:
private fun createPendingIntent() : PendingIntent {
val stackBuilder = TaskStackBuilder.create(applicationContext)
stackBuilder.addNextIntentWithParentStack(applicationContext.packageManager.getLaunchIntentForPackage(applicationContext.packageName))
stackBuilder.addNextIntent(Intent(applicationContext, ActivityB::class.java))
return stackBuilder.getPendingIntent(0, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
}
Notification is showed like this:
private fun showNotification() {
val pIntent = createPendingIntent()
val builder = NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Have a nice day")
.setContentText("Take care")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pIntent)
val notification = builder.build()
with(NotificationManagerCompat.from(this)){
notify(100, notification)
}
}
Upvotes: 3
Views: 787
Reputation: 3592
I think I've found a better way! Instead using TaskStackBuilder I've used PendingIntent.getActivities which allows to give an array of Intents, this worked better and the MainActivity wasn't restarted when going back from top activity.
Here here i use it
private fun createPendingIntent(): PendingIntent {
val rootIntent = applicationContext.packageManager.getLaunchIntentForPackage(applicationContext.packageName)
val nextIntent = Intent(applicationContext, ActivityB::class.java)
return PendingIntent.getActivities(applicationContext, 0, arrayOf(rootIntent, nextIntent), PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT )
}
Upvotes: 1