Search code examples
androidandroid-intentandroid-activityandroid-notificationsandroid-pendingintent

Prevent recreating alive activity when launching from notification


From Android Oreo 8.0 (26 API) when using code for launching activity, it won't create a new activity if previous instance wasn't destroyed and still alive, but on previous Android (e.g. Marshmallow, Nougat) it always creates a new activity in any case.

Why does it behave so differently depending on Android version?

I want to prevent creating a new instance of activity and just bring to front existing (if it's still alive) starting from Android 23 (Marshmallow) when clicking on notification. For now it only works starting from Oreo Android (26)

val intent = Intent(this, TestActivity::class.java).apply {
    flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}

val pendingIntentt = PendingIntent.getActivity(
    this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT
)

val ... = NotificationCompat.Builder(this, channelId)
    ...
    .setContentIntent(pendingIntent)

Solution

  • If you want to bring an existing instance of the app to the foreground, or create a new instance if the app isn't running (foreground or background), then just use a launch Intent in your Notification:

    val intent = getPackageManager.getLaunchIntentForPackage("my.package.name")