Question

I have two Activities, A and B. Here is a normal scenario: A is running, then sends an intent to B. A is paused, and B displays. When the user presses the back button from B, B us destroyed and the user is returned to A.

However, there is a case where B needs to re-create itself. To do this, I call finish() and then startActivity() on B and that works fine. But then, when I click the back button, it shows B again, and so I need to click the back button once more to get back to A.

How can I re-start B, but still be able to press the back button only once to return to A?

Was it helpful?

Solution

The following will dispose of the current activity while launching the next intent:

Intent launchNext = new Intent(getApplicationContext(), NextActivity.class);
launchNext.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(launchNext);

To override the back button, use the following:

@Override
public void onBackPressed() {
    super.onBackPressed();
    this.finish(); // or do something else
}

OTHER TIPS

This can be solved by taking a closer look at your intent flags. Check out http://developer.android.com/reference/android/content/Intent.html and they give more information about what lifecycle you are shooting for.

Also, don't forget that you can override the back button functionality. This may be helpful in case you want to manage your life cycle more closely. For example, you can also make sure to go back to A if back from B. And close your app if back on A.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top