Removing an activity from the history stack

后端 未结 15 944
[愿得一人]
[愿得一人] 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:48

    I use this way.

    Intent i = new Intent(MyOldActivity.this, MyNewActivity.class);
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK)
    startActivity(i);
    
    0 讨论(0)
  • 2020-11-22 08:51
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                super.finishAndRemoveTask();
            }
            else {
                super.finish();
            }
    
    0 讨论(0)
  • 2020-11-22 08:52

    Yes, have a look at Intent.FLAG_ACTIVITY_NO_HISTORY.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 08:56

    Try this:

    intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY)

    it is API Level 1, check the link.

    0 讨论(0)
  • 2020-11-22 09:00

    You can use forwarding to remove the previous activity from the activity stack while launching the next one. There's an example of this in the APIDemos, but basically all you're doing is calling finish() immediately after calling startActivity().

    0 讨论(0)
提交回复
热议问题