Question

I have implemend the up button according to Google recommandations found here: http://developer.android.com/training/implementing-navigation/ancestral.html

Like this:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        // This is called when the Home (Up) button is pressed
        // in the Action Bar.
    case android.R.id.home:
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(
                Intent.FLAG_ACTIVITY_CLEAR_TOP |
                Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        finish();
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

The big problem with this code is that the MainActivity is started from a new instance. I would like to open the previous Instance of MainActivity without restarting it.

As this ACtivity is quite heavy, I do not want to create a new one every time the user press on the up button.

I tried to remove the flag FLAG_ACTIVITY_NEW_TASK and played a lot with all imaginable flags, but I did not succeed to create a button that would bring back the MainACtivity in previous state.

Any help would be highly appreciated.

Was it helpful?

Solution

What you're looking for is the flag:

Intent.FLAG_ACTIVITY_REORDER_TO_FRONT

Which will do what you want - if the activity already exists in the task and stack, then it will be brought to the front, otherwise it will be recreated.

Bear in mind that if the Activity has been destroyed by the GC, then it'll be recreated anyway, and some UI components may be reset depending on where you've got intialisation code (I don't think that onCreate() is called, but onResume() definitely will be

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