How to restart Activity in Android

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

    This solution worked for me.

    First finish the activity and then start it again.

    Sample code:

    public void restartActivity(){
        Intent mIntent = getIntent();
        finish();
        startActivity(mIntent);
    }
    
    0 讨论(0)
  • 2020-11-22 08:27

    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,

    0 讨论(0)
  • 2020-11-22 08:27
    public void onRestart() {
        super.onRestart();
        Intent intent=new Intent();
        intent.setClass(act, act.getClass());
        finish();
        act.startActivity(intent);
    }
    

    try to use this ..

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

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

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

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

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

    There is one hacky way that should work on any activity, including the main one.

    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
    

    When orientation changes, Android generally will recreate your activity (unless you override it). This method is useful for 180 degree rotations, when Android doesn't recreate your activity.

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