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:31

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!)

查看更多
还给你的自由
3楼-- · 2018-12-31 10:31

Call this method

private void restartFirstActivity()
 {
 Intent i = getApplicationContext().getPackageManager()
 .getLaunchIntentForPackage(getApplicationContext().getPackageName() );

 i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK );
 startActivity(i);
 }

Thanks,

查看更多
宁负流年不负卿
4楼-- · 2018-12-31 10:36

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);
}
查看更多
大哥的爱人
5楼-- · 2018-12-31 10:38

Even though this has been answered multiple times.

If restarting an activity from a fragment, I would do it like so:

new Handler().post(new Runnable() {

         @Override
         public void run()
         {
            Intent intent = getActivity().getIntent();
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
            getActivity().overridePendingTransition(0, 0);
            getActivity().finish();

            getActivity().overridePendingTransition(0, 0);
            startActivity(intent);
        }
    });

So you might be thinking this is a little overkill? But the Handler posting allows you to call this in a lifecycle method. I've used this in onRestart/onResume methods when checking if the state has changed between the user coming back to the app. (installed something).

Without the Handler if you call it in an odd place it will just kill the activity and not restart it.

Feel free to ask any questions.

Cheers, Chris

查看更多
美炸的是我
6楼-- · 2018-12-31 10:38

If you are calling from some fragment so do below code.

Intent intent = getActivity().getIntent();
getActivity().finish();
startActivity(intent);
查看更多
公子世无双
7楼-- · 2018-12-31 10:39

This is by far the easiest way to restart the current activity:

finish();
startActivity(getIntent());
查看更多
登录 后发表回答