How to restart Activity in Android

后端 未结 21 2243
日久生厌
日久生厌 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:38

    If anybody is looking for Kotlin answer you just need this line.

    Fragment

    startActivity(Intent.makeRestartActivityTask(activity?.intent?.component))
    

    Activity

    startActivity(Intent.makeRestartActivityTask(this.intent?.component))
    
    0 讨论(0)
  • 2020-11-22 08:41

    In conjunction with strange SurfaceView lifecycle behaviour with the Camera. I have found that recreate() does not behave well with the lifecycle of SurfaceViews. surfaceDestroyed isn't ever called during the recreation cycle. It is called after onResume (strange), at which point my SurfaceView is destroyed.

    The original way of recreating an activity works fine.

    Intent intent = getIntent();
    finish();
    startActivity(intent);
    

    I can't figure out exactly why this is, but it is just an observation that can hopefully guide others in the future because it fixed my problems i was having with SurfaceViews

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题