Android redirect to new activity and stop current activity
To redirect to a new activity and stop the current activity in Android, you can use the finish()
method to stop the current activity and then use the Intent
class to start the new activity.
Here is an example:
Intent intent = new Intent(this, NewActivity.class);
startActivity(intent);
finish();
This code creates a new Intent
object that starts the NewActivity
class, and then starts the activity using the startActivity()
method. Finally, it calls the finish()
method to stop the current activity.
You can also use the Intent.FLAG_ACTIVITY_NEW_TASK
flag to start the new activity in a new task, which will stop the current activity:
Intent intent = new Intent(this, NewActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
Alternatively, you can use the Intent.FLAG_ACTIVITY_CLEAR_TOP
flag to clear the current activity stack and start the new activity:
Intent intent = new Intent(this, NewActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
Note that the finish()
method will only work if the activity is not running in the background. If the activity is running in the background, you will need to use a different approach to stop it.
Also, you can use overridePendingTransition()
method to animate the transition between the two activities:
Intent intent = new Intent(this, NewActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
finish();
This will animate the transition from the current activity to the new activity by sliding the new activity in from the right and the current activity out to the left.