Search code examples
androidandroid-activityback-buttonactivity-lifecycleup-button

Activity Lifecyle Difference in Device's Back Button vs Actionbar's Back Button


I'm currently learning the Activity Lifecyle. I noticed the following:

  • I have two Activitys, A and B.
  • When I open Activity B from Activity A, A gets stopped and B gets created and started.
  • When I press the Back Button on my device, B gets destroyed and A get restarted.
  • But when I use the Back / Up Botton of the Actionbar instead, B gets destroyed, A gets destroyed and then onCreate() is called.

Why gets A destroyed instead of restarted, when using the Up Botton in the ActionBar?

I hope my question is clear, if not please comment.


Solution

  • When you press the BACK button, this calls onBackPressed() in the current Activity. The default behaviour of that method (if not overridden in the Activity) is to call finish() on the Activity. This finishes the Activity and resumes the Activity which is underneath it.

    The UP button is calling startActivity() with an Intent that is built like this:

    Intent intent = new Intent(this, TargetActivityForUpButton.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    

    This code will remove all activities in the stack back to, and including, TargetActivityForUpButton. It then creates a new instance of TargetActivityForUpButton and launches that Actvity (you will see onCreate(), onStart(), onResume() called on the Activity.

    See also the section "Navigate up to parent activity" in https://developer.android.com/training/implementing-navigation/ancestral