Removing an activity from the history stack

后端 未结 15 976
[愿得一人]
[愿得一人] 2020-11-22 08:28

My app shows a signup activity the first time the user runs the app, looks like:

  1. ActivitySplashScreen (welcome to game, sign up for an account?)
  2. Activ
15条回答
  •  一生所求
    2020-11-22 08:52

    It is crazy that no one has mentioned this elegant solution. This should be the accepted answer.

    SplashActivity -> AuthActivity -> DashActivity

    if (!sessionManager.isLoggedIn()) {
        Intent intent = new Intent(context, AuthActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        context.startActivity(intent);
        finish();
    } else {
       Intent intent = new Intent(context, DashActivity.class);
       context.startActivity(intent);
        finish();
    }
    

    The key here is to use intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); for the intermediary Activity. Once that middle link is broken, the DashActivity will the first and last in the stack.

    android:noHistory="true" is a bad solution, as it causes problems when relying on the Activity as a callback e.g onActivityResult. This is the recommended solution and should be accepted.

提交回复
热议问题