1

I understand that when a device rotates, Android destroys and recreates the current activity in order to load orientation-specific resources. To save state, I can use onSaveInstanceState(Bundle outState)and the regular onCreate(Bundle savedInstanceState) but this saves and restores state each time the app is destroyed/created for any reason.

What I want to do is to save/restor state only when the app was destroyed/created because of an orientation change; when the app is destroyed because of memory or the user kills it, I'm not interested in saving state. ¿How can I do this?

Léster
  • 1,177
  • 1
  • 17
  • 39
  • You only save member variables, data or dynamic content. Anything with an ID android automatically takes care of saving for you. There are callbacks (`onLowMemory`) that allow you to be informed of low memory within the Activity class. – TheSunny Jan 28 '16 at 23:53

2 Answers2

0

You could set the onConfigurationChange() method. To do that you need to override it in your Activity's code and set a few parameters in your Manifest:

MainActivity.java

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
    }
}

You have to add these attributes (android:configChanges="orientation|screenSize") to your activity, set as many as you want to handle:

AndroidManifest.xml

<activity android:name=".MyActivity"
          android:configChanges="orientation|screenSize"
          android:label="@string/app_name">

Be careful, with this setup, your activity will not restart, as mentioned in the docs, so, if you want to restart it you will need to implement a manual restart.

Now, when one of these configurations change, MyActivity does not restart. Instead, the MyActivity receives a call to onConfigurationChanged().

Link to the main documentation.

Evin1_
  • 12,292
  • 9
  • 45
  • 47
0

Turns out my question was wrong from the beginning.

When the device rotates, Android calls onSaveInstanceState(Bundle outState) and onRestoreInstanceState(Bundle savedInstanceState) as a way for the developer to save/restore state. When the activity is destroyed via back button or finish(), onSaveInstanceState is not called and the savedInstanceState bundle that's passed to onCreate() is null. So trying to answer the "was this created after a rotation or not?" question is irrelevant.

Posted in case someone has the same question and thanks to all that took time to read and help.

Léster
  • 1,177
  • 1
  • 17
  • 39