views:

1831

answers:

3

how to restart an android Acitivity? 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();

}

A: 

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.

Dimitar Dimitrov
I have a button that applies different themes to the app, after the theme is applied, it's saved in preference, the root activity restarts, reads the theme from preference, applies the theme in onCreate(). It turns out that the above code works fine if the activity is not single_instance. Not sure if that's the best practice.
Currently, there is no clean, SDK-paved way to restart your Activity, AFAIK - if you don't leak anything, you may be good to go :)
Dimitar Dimitrov
A: 

actually a cleaner way to do this is like so:

    public void reload() {

    onStop();
    onCreate(getIntent().getExtras());
}
Ben
A: 

I did my theme switcher like this:

Intent intent = getIntent();
finish();
startActivity(intent);

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?

EboMike