Search code examples
androidandroid-activityactivity-finish

finish() activity twice in android?


Okay say your using a app, and you opened a new activity and then opened another, you can end the activity your on by using finish(); and your back one activity, but how can you go back two activities, all the way back to the first one? I know you could use:

Intent savedGameIntent = new Intent(v.getContext(), firstclass.class);
v.getContext().startActivity(savedGameIntent);

But is that the best way to do it?


Solution

  • Use the flag Intent.FLAG_ACTIVITY_CLEAR_TOP.

      Intent intent = new Intent(this,A.class);
      intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
      startActivity(intent);
    

    From the documentation:

    If set, and the activity being launched is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent.

    So effectively, if you have A -> B -> C, and you intent to A with that flag set, B and C will close.