Home » Android » start a new activity by closing all the stacked activities

start a new activity by closing all the stacked activities

Posted by: admin November 1, 2017 Leave a comment

Questions:

My activity stack:

Main -> Restaurant Menu -> Order Details.

When order is placed I need to close the Restaurant Menu and Order Details
and Start new activity called Active Order

Main -> Active Order.  (need to close top 2 activity)

I have tried with all the options like below

    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |  Intent.FLAG_ACTIVITY_SINGLE_TOP);

All the solution I found behaving like below

  1. Main -> Restaurant Menu -> Active Order. (close Order details)
  2. only Active Order. (close everything and start new)

How can I achieve this.
Main -> Active Order. ?

Thanks.

Answers:

My idea that you could use is to set a SharedFile each time a new intent starts, and after you use startActivity();, I would put finish(); after to close the current activity before it opens the new one.

Questions:
Answers:

I have used bellow like..

    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
    this.startActivity(intent);
    this.finish();

Questions:
Answers:
 Intent i = new Intent(getActivity(), ActiveOrder.class);
                        i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(i);

Questions:
Answers:

You can launch an activity like that:

 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  

This is a minimal example how you can create an Intent and start an Activity in Android.

Intent intent = new Intent(this,Home.class); 
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
startActivity(intent); 

Questions:
Answers:

Try this way

intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);

According to Android Developers resource on Intent:

  • FLAG_ACTIVITY_CLEAR_TASK : If set in an Intent passed to Context.startActivity(), this flag will cause any existing task that would be associated with the activity to be cleared before the activity is started.
  • FLAG_ACTIVITY_NEW_TASK : If set, this activity will become the start of a new task on this history stack.

After calling startActivity(intent) put this line for better accuracy:

YourActivity.this.finish();