How to restart Activity in Android
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:
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?
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!)
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.
Before SDK 11, a way to do this is like so:
public void reload() {
Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}
Just to combine Ralf and Ben's answers (including changes made in comments):
if (Build.VERSION.SDK_INT >= 11) {
recreate();
} else {
Intent intent = getIntent();
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
overridePendingTransition(0, 0);
}
I used this code so I still could support older Android versions and use recreate()
on newer Android versions.
Code:
public static void restartActivity(Activity activity){
if (Build.VERSION.SDK_INT >= 11) {
activity.recreate();
} else {
activity.finish();
activity.startActivity(activity.getIntent());
}
}
Sample:
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private Activity mActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mActivity = MainActivity.this;
Button button = (Button) findViewById(R.id.restart_button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
restartActivity(mActivity);
}
});
}
public static void restartActivity(Activity activity) {
if (Build.VERSION.SDK_INT >= 11) {
activity.recreate();
} else {
activity.finish();
activity.startActivity(activity.getIntent());
}
}
}