Home >Java >javaTutorial >How to Close All Existing Activities and Redirect to a New Screen in Android?
Managing Activity Transitions: Closing All Activities and Redirecting to a New Screen
In Android development, handling the navigation flow between multiple screens is crucial. A common scenario involves a logout button that should close all active screens and redirect the user to a login screen.
The Challenge
The provided code flow consists of several screens accessible from a home screen: Home -> Screen 1 -> Screen 2 -> Screen 3 -> Screen 4 -> Screen 5. The goal is to add a logout button that, when clicked from any of these screens, closes all existing screens and opens a new "Login" screen.
Solution
To address this challenge, the following code can be implemented:
<code class="java">Intent intent = new Intent(getApplicationContext(), Home.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent);</code>
This code creates an intent to navigate to the "Home" screen and adds the Intent.FLAG_ACTIVITY_CLEAR_TOP flag. This flag ensures that all activities on top of the "Home" screen are cleared from the stack.
Explanation
When the logout button is clicked, the above code is executed. It launches the "Home" screen with the FLAG_ACTIVITY_CLEAR_TOP flag. This flag instructs the system to clear the task stack and display the "Home" screen as the root activity.
As a result, all activities in the flow from Screen 1 to Screen 5 are removed from the activity stack. The user is then redirected directly to the "Login" screen.
Additional Considerations
If desired, you can extend this solution by adding an extra parameter to the intent and using it in the "Home" screen activity to perform additional actions, such as finishing the "Home" screen and relaunching the "Login" screen.
Compatibility
It's important to note that this solution uses Intent.FLAG_ACTIVITY_CLEAR_TOP, which is available in Android API level 1. This means that this approach can be used even on older Android versions, such as 1.6.
The above is the detailed content of How to Close All Existing Activities and Redirect to a New Screen in Android?. For more information, please follow other related articles on the PHP Chinese website!