I want to go back to MainActivity from any activities.
For ex, my stack of activities:
A - B - C - D.
A (MainActivity) is in the bottom and D is in the top of stack .
When I use android:launchMode="singleTask"
. I can go back to A at any actvities as I expected.
But when I use flag FLAG_ACTIVITY_NEW_TASK
(without launchMode="singleTask"), it does not work as expected, it open a new Activity.
And stacks are:
A - B - C - D - A
not as document wrote:
FLAG_ACTIVITY_NEW_TASK
Start the activity in a new task. If a task is
already running for the activity you are now starting, that task is
brought to the foreground with its last state restored and the
activity receives the new intent in onNewIntent().
This produces the same behavior as the "singleTask" launchMode value, discussed in the
previous section.
Anyone knows the reason? Thanks.
I hope this solution solve your problem::- Only set this to Intent
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
Find the solution :
Note : It will clear all previous activity and will lauch HomeActivity
Intent homeActivity = new Intent(context, DJ_HomeActivity.class);
homeActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(homeActivity);
Try this in one.You can add and remove activity from stack like this.
// Add activity
public static void addActivities(String actName, Activity _activity) {
if (Config.screenStack == null)
Config.screenStack = new HashMap<String, Activity>();
if (_activity != null)
Config.screenStack.put(actName, _activity);
}
// Remove Activity
public static void removeActivity(String key) {
if (Config.screenStack != null && Config.screenStack.size() > 0) {
Activity _activity = Config.screenStack.get(key);
if (_activity != null) {
_activity.finish();
}
}
}
User add activities before setContentView to add into the stack.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addActivities("DemoActivity", DemoActivity.this)
setContentView(R.layout.activity_create_feed_post);
}
For remove activity you just call the removeActivity() and pass the key which you use when add the activity.
Override onBackpress
method of each activity :
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
you should use below code to jump on the MainActivity.With the intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
following flag of intent it clears the all previous activity.
Intent intent = new Intent(this, DashboardActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
Note one thing, You used android:launchMode="singleTask"
So while moving from A activity to another activity you must have to finish A Activity by using this.finish()
method.