How do I restart an Android Activity
? I tried the following, but the Activity
simply quits.
public static void restartActivity(Act
Well this is not listed but a combo of some that is already posted:
if (Build.VERSION.SDK_INT >= 11) {
recreate();
} else {
Intent intent = getIntent();
finish();
startActivity(intent);
}
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);
}
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.
The solution for your question is:
public static void restartActivity(Activity act){
Intent intent=new Intent();
intent.setClass(act, act.getClass());
((Activity)act).startActivity(intent);
((Activity)act).finish();
}
You need to cast to activity context to start new activity and as well as to finish the current activity.
Hope this helpful..and works for me.
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());
}
}
}