Programmatically relaunch/recreate an activity?

Call the recreate method of the activity.


Option 1

Call recreate() on your Activity. However this method causes a flashing black screen to appear during the activity re-creation.

Option 2

finish();
startActivity(getIntent());

No "flashing" black screen here, but you'll see a transition between the old and the new instances with a not-so-pleasant black background. We can do better.

Option 3

To fix this, we can add a call to overridePendingTransition() :

finish();
startActivity(getIntent());
overridePendingTransition(0, 0);

Good bye black screen, but in my case I still see some kind of transition (a fade animation), on a colored background this time. That's because you're finishing the current instance of your activity before the new one is created and becomes fully visible, and the in-between color is the value of the windowBackground theme attribute.

Option 4

startActivity(getIntent());
finish();

Calling finish() after startActivity() will use the default transition between activities, often with a little slide-in animation. But the transition is still visible.

Option 5

startActivity(getIntent());
finish();
overridePendingTransition(0, 0);

To me, this is the best solution because it restarts the activity without any visible transition, like if nothing happened.

It could be useful if, for example, in your app you expose a way to change the display language independently of the system's language. In this case, whenever the user changes your app's language you'll probably want to restart your activity without transition, making the language switch look instantaneous.


UPDATE: Android SDK 11 added a recreate() method to activities.


I've done that by simply reusing the intent that started the activity. Define an intent starterIntent in your class and assign it in onCreate() using starterIntent = getIntent();. Then when you want to restart the activity, call finish(); startActivity(starterIntent);

It isn't a very elegant solution, but it's a simple way to restart your activity and force it to reload everything.

Tags:

Android