Krunal Shah
Krunal Shah

Reputation: 1436

How to clear BackStack?

in my application there are 4 activities, which are A, B, C, D

From activity "A", its a splash screen

Intent intent = null;
if(userLogin()) {
  intent = new Intent(A.this, B.class);
  startActivity(intent);
  finish();
}
else {
  intent = new Intent(A.this, c.class);
  startActivity(intent);
  finish();
}

both "A" and "B" call same activity "D" and it is Login or Logout screen From activity "D"

String calledActivity = getIntent().getStringExtra("CALLED_ACTIVITY");

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
  if(keyCode == KeyEvent.KEYCODE_BACK) {
    if(calledActivity.equal("C") && userLogin()) {
      Intent intent = new Intent(D.this, B.class);
      intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
      startActivity(intent);
      finish();
    }
    else if(calledActivity.equal("B") && !userLogin()) {
      Intent intent = new Intent(D.this, C.class);
      intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
      startActivity(intent);
      finish();
    }
    else 
      finish();
    return true;
  }
  return false;
}

Before calling "D" if user not login, The stack is "C"

After Calling "D" if usr not login, The stack is "C" -> "D"

after press back from activity "D" if user login, The stack is "C" -> "B"

But originally i want to, The stack is "B"

Please help me to sort out this problem, Thank you

Upvotes: 2

Views: 206

Answers (2)

Akshay Paliwal
Akshay Paliwal

Reputation: 3926

Start new Activity with this code. and all stacks will be cleared.

Intent intent = new Intent(getBaseContext(), Registration.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent);

Upvotes: 2

vipul mittal
vipul mittal

Reputation: 17401

Start B with following flags:

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

This will clear all the views before B and stack will only contain B.

Although FLAG_ACTIVITY_CLEAR_TASK is available from API 11.

Upvotes: 2

Related Questions