[Java] [Android] Terminate the activity of the transition source at the time of screen transition

1 minute read

When creating an application on Android, there are cases where you want to exit the application with the back button.

Ex) Exit the application by pressing the back button after transition from the login screen. (Do not return to the login screen)

In such a case, I have summarized the method to terminate Activity.

When transitioning from # Activity to Activity


Intent intent = new Intent(getApplication(), SubActivity.class);

Activating A and B at the time of transition from screen A to B to C (when you want to terminate multiple activities)

Ex) When signing in with A (initial screen) → B (sign-in screen) → C (main screen) and then exiting the application with the return button.


  Intent intent = new Intent(getApplication(), CActivity.class);

With finish(), A (initial screen) will be displayed when you press the return button on the main screen. This is because the activity is closed only on the sign-in screen.

FLAG_ACTIVITY_NEW_TASK: Create a new task and add the starting Activity to that task's stack
FLAG_ACTIVITY_CLEAR_TASK: Destroy an existing task before launching the Activity. This flag can only be used in combination with FLAG_ACTIVITY_NEW_TASK.

End Activity on transition from #Fragment


Intent intent = new Intent(getActivity(), SecondActivity.class);
                                MainActivity mainActivity = (MainActivity) getActivity();

Since finish() cannot be used in Fragment, it is necessary to instantiate and use the Activity.


Basically you can finish the activity with finish().

For example, when you log out, and when you press the back button after transitioning to the login screen, you do not want to return to the logout screen, so I think you can use this implementation!


I want to prevent returning to the login screen after Android login