When creating an app on Android, you may want to close the app with the back button.
Ex) Exit the app by pressing the back button after the transition from the login screen. (Do not return to the login screen)
In such a case, we have summarized how to terminate the Activity.
MainActivity.java
Intent intent = new Intent(getApplication(), SubActivity.class);
startActivity(intent);
finish();
Ex) When you exit the app with the back button after signing in with A (initial screen) → B (sign-in screen) → C (main screen).
BActivity.java
Intent intent = new Intent(getApplication(), CActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
With finish ()
, if you press the back button on the main screen, A (initial screen) will be displayed.
This is because Activity is closed only on the sign-in screen.
FLAG_ACTIVITY_NEW_TASK:Create a new task and add the activity to launch to the task's stack
FLAG_ACTIVITY_CLEAR_TASK:Destroy an existing task before launching the Activity. This flag is FLAG_ACTIVITY_NEW_Can only be used in combination with TASK.
currentFragment.java
Intent intent = new Intent(getActivity(), SecondActivity.class);
startActivity(intent);
MainActivity mainActivity = (MainActivity) getActivity();
mainActivity.finish();
Since finish ()
is not available in Fragment, you need to instantiate and use Activity.
Basically, you can finish the activity with finish ()
.
For example, if you log out and press the back button after transitioning to the login screen, you do not want to be returned to the logout screen, so I think you can use this implementation!
I want to prevent returning to the login screen after logging in to Android
Recommended Posts