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();
}
I did my theme switcher like this:
Basically, I'm calling
finish()
first, and I'm using the exact same intent this activity was started with. That seems to do the trick?UPDATE: As pointed out by Ralf below,
Activity.recreate()
is the way to go in API 11 and beyond. This is preferable if you're in an API11+ environment. You can still check the current version and call the code snippet above if you're in API 10 or below. (Please don't forget to upvote Ralf's answer!)Call this method
Thanks,
Before SDK 11, a way to do this is like so:
Even though this has been answered multiple times.
If restarting an activity from a fragment, I would do it like so:
So you might be thinking this is a little overkill? But the
Handler
posting allows you to call this in a lifecycle method. I've used this inonRestart
/onResume
methods when checking if the state has changed between the user coming back to the app. (installed something).Without the
Handler
if you call it in an odd place it will just kill the activity and not restart it.Feel free to ask any questions.
Cheers, Chris
If you are calling from some fragment so do below code.
This is by far the easiest way to restart the current activity: