Finishing all activities started before the activity

前端 未结 3 1539
难免孤独
难免孤独 2021-02-09 15:16

I want to finish all the activities which are running in the application means want to remove all the parent activities from stack.

I want to implement logout functional

3条回答
  •  隐瞒了意图╮
    2021-02-09 16:13

    I should let you know this is not a recommended behavior in android since you should let itself to manage life circles of activities.

    However if you really need to do this, you can use FLAG_ACTIVITY_CLEAR_TOP

    I give you some sample code here, where MainActivity is the first activity in the application:

    public static void home(Context ctx) {
        if (!(ctx instanceof MainMenuActivity)) {
            Intent intent = new Intent(ctx, MainMenuActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            ctx.startActivity(intent);
        }
    }
    

    If you want to quit whole application, you can use the following code and check in the MainActivity to quit the application completely:

        public static void clearAndExit(Context ctx) {
        if (!(ctx instanceof MainMenuActivity)) {
            Intent intent = new Intent(ctx, MainMenuActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            Bundle bundle = new Bundle();
            bundle.putBoolean("exit", true);
            intent.putExtras(bundle);
            ctx.startActivity(intent);
        } else {
            ((Activity) ctx).finish();
        }
    }
    

    Hope this helps.

提交回复
热议问题