Replace current activity

AndroidAndroid Activity

Android Problem Overview


I need to replace the current activity with a new one. That is, I want to start a new activity and remove the current activity from the task stack.

Based on the documentation, it seems the best way would be to start the activity using Activity.startActivity as per usual, and then call Activity.finish immediately to close the current activity.

Is this a valid usage of these APIs or should I be doing something else?

Android Solutions


Solution 1 - Android

Yes. It is fine to use api this way.

Solution 2 - Android

The proper way to achieve this is using the following:

Intent intent = new Intent(this,MyActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_TASK_ON_HOME);
startActivity(intent);
this.finish();

The code assumes you are in an activity, otherwise if you are using fragments use getActivity()

This way, the activity is started, you properly set your hierarchy for your back button, and you also destroy the appropriate activity.

Solution 3 - Android

try using FLAG_ACTIVITY_TASK_ON_HOME, FLAG_ACTIVITY_NEW_TASK in the intent flags

Solution 4 - Android

You can add android:launchMode="singleInstance" in your activity, then override onNewIntent method to update date

Reference PlayerActivity in ExoPlayer Demo

Solution 5 - Android

You can use FLAG_ACTIVITY_CLEAR_TASK when you start the activity. I also defined the launchMode for my activity in the manifest as singleTask, but that was because I wanted that behavior for the new activity. I think you can get what you want with regard to clearing the previous activity regardless of what you use for launchMode with your new activity, as long as you pass startActivity the flag FLAG_ACTIVITY_CLEAR_TASK.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRichard SzalayView Question on Stackoverflow
Solution 1 - AndroidTusharView Answer on Stackoverflow
Solution 2 - AndroidJeremie DView Answer on Stackoverflow
Solution 3 - Androiduser838411View Answer on Stackoverflow
Solution 4 - AndroidFangming ChengView Answer on Stackoverflow
Solution 5 - AndroidAndy WeinsteinView Answer on Stackoverflow