Why is onDestroy always called when returning to parent activity?

后端 未结 2 1542
情书的邮戳
情书的邮戳 2020-12-14 17:23

I have a very simple app based on the Building Your First App tutorial. There are two activities: MainActivity invokes DisplayMessageActivity thro

相关标签:
2条回答
  • 2020-12-14 18:01

    Adding launchMode in Manifest changes launch mode every time, even it is not launched by child activity. There are other ways to launch existed instance.

    1.override onOptionsItemSelected(item: MenuItem)

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
       return when (item.itemId) {
            android.R.id.home -> {
                // Respond to the action bar's Up/Home button
                val upIntent: Intent? = NavUtils.getParentActivityIntent(this)
                when {
                    upIntent == null -> throw IllegalStateException("No Parent Activity Intent")
                    else -> {
                        //add launch flag here
                        upIntent.flags=Intent.FLAG_ACTIVITY_CLEAR_TOP
                        NavUtils.navigateUpTo(this, upIntent)
                    }
                }
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }
    
    1. 2nd solution looks like a bug. Set "android:parentActivityName" to activity which is not existed in current task stack. Android will behavior like "BACK" button. It launches the top instance instead of launching parent activity. Document mentions "NavUtils.shouldUpRecreateTask" can recognize if parent activity existed in current task. But it doesn't work in my test. Navigate up with a new back stack
    0 讨论(0)
  • 2020-12-14 18:02

    Thanks to Greg Giacovelli's comments, I found the answer here. The solution was to set android:launchMode="singleTop" to the parent activity.

    I still can't understand why such basic information is so unknown and hard to find!

    0 讨论(0)
提交回复
热议问题