How do I tell when a configuration change is happening in Froyo?

前端 未结 5 1515
梦谈多话
梦谈多话 2021-02-08 13:18

In my app, I want a media file to play, and to keep playing if the user rotates the screen (destroying the Activity), but I want it to stop playing if the user moves to a differ

5条回答
  •  悲&欢浪女
    2021-02-08 14:01

    I finally figured out the answer to my own question!

    public class MyActivity extends Activity {
    
      Display display; 
      int originalRotation;
    
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
          originalRotation = display.getRotation();
      }
    
      public boolean endingDueToConfigurationChanging() {
       int newRotation = display.getRotation();
       return (newRotation != originalRotation);
      }
    }
    

    Display.getRotation() is designed to return a constant indicating whether the device is 0, 90, 180 or 270 degrees off its natural rotation. However, when the device is rotated, this value is updated before the activity ends--it's actually updated as early as in onPause()! So if you compare the value in onPause() (the new value) with the one in onCreate() (the original value) then you know the Activity it shutting down due to a screen rotation or not.

提交回复
热议问题