Android: Clear Activity Stack

2019-01-04 17:23发布

I'm having several activities in my application. and flow is very complicated. When I click the Logout application naviagates to login Screen and from there user can exit by cancel buton (calling system.exit(0) )

when I exit or back button, system invokes an activity from stack :( how can I clear all the activities in the stack when i reach Login screen? calling finish() is not practical as there are so many activities and some activities should no be closed when they are active such as native camera invoking activity.

validateuser logoutuser = new validateuser();
logoutuser.logOut();
Intent loginscreen = new Intent(homepage.this, Login2.class);
(homepage.this).finish();
loginscreen.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(loginscreen);

9条回答
放我归山
2楼-- · 2019-01-04 18:13

Clear Activity Backstate by below code:

Intent intent = new Intent(Your_Current_Activity.this, Your_Destination_Activity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK |Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

Done

查看更多
闹够了就滚
3楼-- · 2019-01-04 18:15
Intent intent = new Intent(LoginActivity.this, Home.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  //It is use to finish current activity
startActivity(intent);
this.finish();
查看更多
倾城 Initia
4楼-- · 2019-01-04 18:16

I noted that you asked for a solution that does not rely on finish(), but I wonder if this may help nonetheless.

I tracked whether an exit flag is raised with a static class variable, which survives the entire app lifespan. In each relevant activity's onResume(), use

@Override
public void onResume() {
    super.onResume();
    if (ExitHelper.isExitFlagRaised) {
        this.finish();
    }
}

The ExitHelper class

public class ExitHelper {
    public static boolean isExitFlagRaised = false;
}

Let's say in mainActivity, a user presses a button to exit - you can set ExitHelper.isExitFlagRaised = true; and then finish(). Thereafter, other relevant activities that are resumed automatically will be finished as well.

查看更多
登录 后发表回答