Android screen orientation data lose prevention

2019-05-21 06:39发布

问题:

I am trying to stop my app from resetting whenever the user flips the screen. I don't really want to set it to portrait permanently.

My problem is I have settings which erase and a service which stops each time the screen flips. I would like to keep things as they are regardless of the screen orientation.

回答1:

On your Activity in your AndroidManifest, set the following:

<activity android:name="YourActivity" android:configChanges="orientation|keyboardHidden"></activity>

This tells your Activity to not "re-create" itself on screen orientation changes or keyboard change state



回答2:

You can save the data by using :

@Override
public Object onRetainNonConfigurationInstance() {
    return super.onRetainNonConfigurationInstance();
}

return the data you want to save.

In the onCreate function you can check if there is any data saved by doing the following

final Object data = (Object) getLastNonConfigurationInstance());
    if (data == null) {
        //Retrieve data
    }else{
        //Use the saved data
        settings = data;
        }

You can read about this topic at the Android Dev Guide :