NullPointerException
NullPointerException

Reputation: 37701

How to return to an activity closing the in between activities?

I need to go back to the main activity of my app, but for that, I need to close all the activities in between the current activity and the main activity.

I tried with this:

Intent intent = new Intent(getActivity(), MainMenuActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity( intent );

The problem is that doing this, the main activity is also closed and reopenned, calling to onDestroy() in the main destiny activity. I need to go back to it without closing and reopening it. How to achieve it?

Upvotes: 2

Views: 556

Answers (2)

Bö macht Blau
Bö macht Blau

Reputation: 13019

The documentation on FLAG_ACTIVITY_CLEAR_TOP says

The currently running instance [...] will either receive the new intent you are starting here in its onNewIntent() method, or be itself finished and restarted with the new intent. If it has declared its launch mode to be "multiple" (the default) and you have not set FLAG_ACTIVITY_SINGLE_TOP in the same intent, then it will be finished and re-created; for all other launch modes or if FLAG_ACTIVITY_SINGLE_TOP is set then this Intent will be delivered to the current instance's onNewIntent().

In your case, I assume that your MainMenuActivity has a "multiple" launch mode. Since you did not set FLAG_ACTIVITY_SINGLE_TOP, it was finished and restarted.

So if you use

intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|FLAG_ACTIVITY_SINGLE_TOP);

then according to the documentation the MainMenuActivity instance will keep its state and onNewIntent() will be called.

Note: you can use setIntent() to make the Intent which is passed into onNewIntent() "the" Intent of the Activity

Upvotes: 2

GensaGames
GensaGames

Reputation: 5788

Did you try set launchMode for the MainActivity. Please note, this should be done for all transaction within particular Activity. Check the options for from documentation.

An instruction on how the activity should be launched. There are four modes that work in conjunction with activity flags (FLAG_ACTIVITY_* constants) in Intent objects to determine what should happen when the activity is called upon to handle an intent. They are:

"standard"
"singleTop"
"singleTask"
"singleInstance"

Upvotes: 0

Related Questions