How do I restart an Android Activity
? I tried the following, but the Activity
simply quits.
public static void restartActivity(Activity act){
Intent intent=new Intent();
intent.setClass(act, act.getClass());
act.startActivity(intent);
act.finish();
}
Call the method onCreate. For example
onCreate(null);
Since API level 11 (Honeycomb), you can call the recreate() method of the activity (thanks to this answer).
The recreate() method acts just like a configuration change, so your onSaveInstanceState() and onRestoreInstanceState() methods are also called, if applicable.
I wonder why no one mantionned
Intent.makeRestartActivityTask()
which cleanly makes this exact purpose.startActivity(Intent.makeRestartActivityTask(getActivity().getIntent().getComponent())
This method sets
Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK
as default flags.Well this is not listed but a combo of some that is already posted:
The solution for your question is:
You need to cast to activity context to start new activity and as well as to finish the current activity.
Hope this helpful..and works for me.
If you remove the last line, you'll create new
act
Activity, but your old instance will still be alive.Do you need to restart the Activity like when the orientation is changed (i.e. your state is saved and passed to
onCreate(Bundle)
)?If you don't, one possible workaround would be to use one extra, dummy Activity, which would be started from the first Activity, and which job is to start new instance of it. Or just delay the call to
act.finish()
, after the new one is started.If you need to save most of the state, you are getting in pretty deep waters, because it's non-trivial to pass all the properties of your state, especially without leaking your old Context/Activity, by passing it to the new instance.
Please, specify what are you trying to do.