Closing All Activities and Launching a Specific Activity in Android
This can be helpful when you want to start a fresh navigation flow or redirect the user to a specific entry point within your app.
1: Close All Activities
To close all activities and bring the user to a specific activity, we'll use the
// Close all activities and launch the desired activity Intent intent = new Intent(context, TargetActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent);
2: Define the Target Activity
Make sure to replace
TargetActivity.class with the name of the activity you want to launch.
3: Handle Activity Stack
FLAG_ACTIVITY_CLEAR_TASK clears the existing activity stack, and
FLAG_ACTIVITY_NEW_TASK starts the target activity as a new task, ensuring a fresh navigation flow.
4: Implement in Your App
Add this code snippet where you want to close all activities and launch the specific activity, such as a logout button or a navigation flow reset.
By using the
Intent.FLAG_ACTIVITY_NEW_TASK flags, you can easily close all activities and launch any specific activity in your Android app. This method provides a clean navigation experience and can be useful in various scenarios, such as logouts, splash screens, or redirections to specific entry points within your app. Happy coding!