How do I restart an Android Activity
? I tried the following, but the Activity
simply quits.
public static void restartActivity(Act
This is the way I do it.
val i = Intent(context!!, MainActivity::class.java)
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
startActivity(i)
Actually the following code is valid for API levels 5 and up, so if your target API is lower than this, you'll end up with something very similar to EboMike's code.
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
overridePendingTransition(0, 0);
If you are calling from some fragment so do below code.
Intent intent = getActivity().getIntent();
getActivity().finish();
startActivity(intent);
I wonder why no one mentioned Intent.makeRestartActivityTask()
which cleanly makes this exact purpose.
Make an Intent that can be used to re-launch an application's task * in its base state.
startActivity(Intent.makeRestartActivityTask(getActivity().getIntent().getComponent()));
This method sets Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK
as default flags.
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.
This is by far the easiest way to restart the current activity:
finish();
startActivity(getIntent());