How do I restart an Android Activity

2018-12-31 10:01发布

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();

}

20条回答
残风、尘缘若梦
2楼-- · 2018-12-31 10:39

Call the method onCreate. For example onCreate(null);

查看更多
旧人旧事旧时光
3楼-- · 2018-12-31 10:41

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.

查看更多
其实,你不懂
4楼-- · 2018-12-31 10:41

I wonder why no one mantionned Intent.makeRestartActivityTask() which cleanly makes this exact purpose.

Make an Intent that can be used to re-launch an application's task * in its base state.

startActivity(Intent.makeRestartActivityTask(getActivity().getIntent().getComponent())

This method sets Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK as default flags.

查看更多
唯独是你
5楼-- · 2018-12-31 10:43

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);
}
查看更多
泛滥B
6楼-- · 2018-12-31 10:43

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.

查看更多
不再属于我。
7楼-- · 2018-12-31 10:44

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.

查看更多
登录 后发表回答