问题
I've read the Android Docs on the lifecycle of an activity. However, I am curious as to how different activities within an application behaves.
From some tests that I've done, transitioning from Activity A to Activity B within the same application via an intent pauses Activity A via onPause()
and creates Activity B via onCreate()
.
The strange part is when Activity B transitions back to Activity A.
If the hardware back key is pressed, onPause()
is fired for Activity B and onResume()
is fired for Activity A. This is what I would expect.
However, if the back button on the ActionBar
is pressed, onDestroy()
is fired for Activity A followed by onCreate()
and onResume()
.
Why is this so?
回答1:
The "back button" on the ActionBar
is called the "Up Button". This is the expected behaviour of the Up Button, if you take a look of the implementation of the code which performs the "up", you see that Activity A is recreated.
Intent parentActivityIntent = new Intent(getApplicationContext(), MainActivity.class);
parentActivityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(parentActivityIntent);
finish();
You can define what the "Up" button should do, however, I suggest to stick to the default behaviour.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// Your Code Here.
break;
}
}
Why?
The Up Button (in contrast to the back button) should navigate one level higher in the application hierarchy, always. The back button should go back, even if it will leave the current application.
You can't just call finish on the current Activity
, because the parent Activity
could already be garbage collected and don't exist anymore.
I heavily suggest to read the official Android Design Guidelines, especially the part about Up vs Back.
来源:https://stackoverflow.com/questions/23615566/android-application-lifecycle-and-back-button