danh32 danh32 - 1 year ago 65
Android Question

How to clear all activities in Android app

My app has many activities that can be called in any order

Example Activity History:
A -> B -> C -> D -> A -> B -> E

Now in activity E, I am 'deregistering' the device (logging the user out, and deleting any data they might have downloaded to their sdcard). The desire behavior is that the app 'starts over' and the user is prompted with a login activity and hitting back will return the user to the home screen.

So now, activity E should clear the activity stack in some way. Currently, I am setting FLAG_ACTIVITY_CLEAR_TOP when launching A's intent from E. The problem is, when the user had visited A and then gone to intermediate activities and revisited A before going to E, there are still activities on the stack.

A -> B -> C -> D -> A

So the user has been logged out and can't use activities B-D, but if the user hits back from activity A, they can access activities B-D. Is there a simple way to have all the activities other than the login activity be cleared from the stack?


So I've tried updating my BaseActivity (each activity in my app subclasses this one) to contain a static flag isDeregistering that tells the activity to destroy itself if true. The problem is, every activity calls finish(), and I get booted to the homescreen and cannot restart the app until force closing the app. Is there a better way to do this?

Answer Source

I've figured out a workable solution. The following code goes into my BaseActivity class.

    public boolean killIfDeregistering() {
    if (isDeregistering) {
        Log.d(TAG, "deregistering true!");
        if (getClass().getName().equals(LoginActivity.class.getName())) {
            //don't destroy activity, reset flag
            Log.d(TAG, "stopping deregister process!");
            isDeregistering = false;
        } else {
            //finish the activity
            Log.d(TAG, "killing this activity!");
            return true;
    return false;

Using a bit of Reflection, I can decide whether or not to kill the base activity, so that the home launcher can restart the app at the LoginActivity. I just have to make sure that the LoginActivity does not remain in the stack after it has performed the login by calling finish() on it manually.