How to clear the Android Stack of activities?

Totic picture Totic · Nov 16, 2010 · Viewed 57.7k times · Source

I have an application with several Activities in Android and I want the user to be able to log-out by pressing a menu button. The problem I have is that

A) Android doesn't let you terminate the application and
B) even when I send the user to the LoginActivity again they can always press back and get right back to the previous activity they were in.

I already tried to launch the Activity with the two following flags:

Intent intent  = new Intent(this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);        
startActivity(intent);

I also tried with each one of them by themselves.

I also tried calling finish() after startActivity(intent) as I read in another StackOverflow question.

Answer

deweylewie picture deweylewie · Dec 2, 2010

This should be bitwise OR'd or you end up overwriting the earlier flag.

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

Like so:

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