androidandroid-intentandroid-activitynotificationsextra

Can not remove extras from Activity launched from notification


I have MainActivity which is launched from notification with this extras:

 val intent = Intent(this, MainActivity::class.java)
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
    intent.putExtra(Constants.EXTRA_NEWS_ID, id.toInt())
    val options = Bundle()
    options.putInt(Constants.EXTRA_NEWS_ID, id.toInt())
    val pendingIntent = PendingIntent.getActivity(
        this, id.toInt(), intent,
        PendingIntent.FLAG_ONE_SHOT, options
    )

Then in MainActivity onCreate i check extras and also try to remove extras:

if (intent.hasExtra(Constants.EXTRA_NEWS_ID)) {
        intentFromNotification = true
        Application.newsDetailId = intent.getIntExtra(Constants.EXTRA_NEWS_ID, 0)
        Log.d("NOTIF", "NewsId = ${NzmApplication.newsDetailId}")
        intent.removeExtra(Constants.EXTRA_NEWS_ID)
        intent.replaceExtras(Bundle())
        intent.action = ""
        intent.data = null
        intent.flags = 0
    }

Later after some initial logic i open second ContentActivity like this:

if (intentFromNotification) { // Activity called from notification = automaticly redirect to news detail
                        val intent = Intent(this, ContentActivity::class.java)
                        intent.putExtra(
                            Constants.EXTRA_FRAGMENT,
                            Constants.FRAGMENT_NEWS_DETAIL
                        )
                        intentFromNotification = false
                        startActivity(intent)
                    }

ContentActivity works correctly, displays what is needed, but when i press back on ContentActivity, MainActivity should be opened and wait for user interaction, but it again execute same code block like on first opening and automaticly open ContentActivity. Extras are still there, so basicly app is cycled.

More strange is this, not happen on every device. I have Sony Xperia XZ1 Compact (Android 9), but nobody else from about 250 users does not report such a issue.

EDIT: onBackPress in ContentActivity

 override fun onBackPressed() {
    super.onBackPressed()
    if (supportFragmentManager.backStackEntryCount == 0) {
        this.finish()
    }
}

Solution

  • Problem was in developer settings, "Do not keep activities" I forget to disable this setting after some specific testing Maybe someone will find this helpfull :)