Replace current activity

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?


Solution 1:

Yes. It is fine to use api this way.

Solution 2:

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:

try using FLAG_ACTIVITY_TASK_ON_HOME, FLAG_ACTIVITY_NEW_TASK in the intent flags

Solution 4:

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

Reference PlayerActivity in ExoPlayer Demo