2

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.

Jan Meyer
  • 214
  • 3
  • 10

2 Answers2

2

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

David Wasser
  • 93,459
  • 16
  • 209
  • 274
1

The device's back button is actually taking you back (to the previous activity). The action bar back button works similarly to an "Up" button (within the hierarchy of your app). This is why the action bar's back button won't take you outside of the app, whereas the device's back button will carry on taking you back, even outside of the app. The action bar exists within your app so it follows the activity's lifecycle methods and starts from scratch each time you go back, whereas the device is restarting from where it stopped.

EDIT:

The Back button appears in the system navigation bar and is used to navigate, in reverse chronological order, through the history of screens the user has recently worked with. It is generally based on the temporal relationships between screens, rather than the app's hierarchy.

(Read more here)

Nikos Hidalgo
  • 3,666
  • 9
  • 25
  • 39