Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear Activity back stack [duplicate]

I start from activity A->B->C->D->E ..when i go from D->E there should be no activity in stack but, the user can use back button from D and go to C (without refreshing Activity C, like normal back function)

like image 483
W00di Avatar asked Aug 14 '13 07:08

W00di


People also ask

How do I delete all Backstacks on Android?

Use finishAffinity() to clear all backstack with existing one. Suppose, Activities A, B and C are in stack, and finishAffinity(); is called in Activity C, - Activity B will be finished / removing from stack. - Activity A will be finished / removing from stack.

What is back stack in Android?

A task is a collection of activities that users interact with when trying to do something in your app. These activities are arranged in a stack—the back stack—in the order in which each activity is opened. For example, an email app might have one activity to show a list of new messages.


2 Answers

You could add a BroadcastReceiver in all activities you want to close (A, B, C, D):

public class MyActivity extends Activity {
    private FinishReceiver finishReceiver;
    private static final String ACTION_FINISH = 
           "com.mypackage.MyActivity.ACTION_FINISH";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        finishReceiver= new FinishReceiver();
        registerReceiver(finishReceiver, new IntentFilter(ACTION_FINISH));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        unregisterReceiver(finishReceiver);
    }

    private final class FinishReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(ACTION_FINISH)) 
                finish();
        }
    }
}

... and close them by calling ...

sendBroadcast(new Intent(ACTION_FINISH));

... in activity E. Check this nice example too.

like image 179
Trinimon Avatar answered Oct 13 '22 14:10

Trinimon


Add flag FLAG_ACTIVITY_CLEAR_TOP to your intent to clear your other Activities form Back stack when you are starting your E Activity like :

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

then start your Activity :

startActivity(intent)

More Information on : Task and BackStack

like image 25
Arash GM Avatar answered Oct 13 '22 14:10

Arash GM