How to restart Activity in Android

后端 未结 21 2475
日久生厌
日久生厌 2020-11-22 08:14

How do I restart an Android Activity? I tried the following, but the Activity simply quits.

public static void restartActivity(Act         


        
21条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 08:43

    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

提交回复
热议问题