How to restart Activity in Android

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

    This is the way I do it.

            val i = Intent(context!!, MainActivity::class.java)
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
            startActivity(i)
    
    0 讨论(0)
  • 2020-11-22 08:32

    Actually the following code is valid for API levels 5 and up, so if your target API is lower than this, you'll end up with something very similar to EboMike's code.

    intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
    overridePendingTransition(0, 0);
    
    0 讨论(0)
  • 2020-11-22 08:35

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

    Intent intent = getActivity().getIntent();
    getActivity().finish();
    startActivity(intent);
    
    0 讨论(0)
  • 2020-11-22 08:36

    I wonder why no one mentioned 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.

    0 讨论(0)
  • 2020-11-22 08:36

    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.

    0 讨论(0)
  • 2020-11-22 08:37

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

    finish();
    startActivity(getIntent());
    
    0 讨论(0)
提交回复
热议问题