Wednesday 22 June 2016

Android Handling Configuration Change

Configuration Changes may include one of these behaviors
  • Changes in Screen Orientation
  • Keyboard Availability Change
  • And the Change in Language
Normally the Configuration Changes results in the call of onDestroy() and onCreate() methods in a order.

To restore the state of the data of your application android call onSaveInstanceState() before onDestroy() and onRestoreInstanceState after onCreate(). It is simple, you can save the data in onSaveInstanceState() method and restore the same in onRestoreInstanceState() or onCreate() method.

 So, how do I handle my Configuration Changed?
 There are 2 methods normally used, First one is Simple method and Second is Compex. Simple is generally preferred if the data that need to be restored during configuration change is less where as Complex is preferred when required to restore large data as the use of simple methods will result lag in the USER Experience of USER INTERFACE.

Method : Simple Method
  • Above and on API 13 add following in Manifest file inside activity with activity Name 
    android:configChanges="orientation|screenSize"
  • Below API 13 add following in Manifest file inside activity with activity Name 
    
    android:configChanges="orientation"
  • And you are done. That's all.
  • If you need to perform some actions on configuration change then only Override the onConfigurationChanged() method of the Activity class inside your Class to perform additional action on Configuration Change but make sure you always call super.onConfigurationChanged();
  • Doing this, the Configuration change event will not call for onCreate() again and application data remains same.
Method : Complex Method
  • When the Configuration Changes and if the manifest file of activity doesn't include configchanges attribute unlike Simple Method above, then the android calls onSaveInstanceState in the event of Configuration Change unspecified in Manifect Activity.
  • Override the onSaveInstanceState() method and add the values to be saved. example
    protected void onSaveInstanceState(Bundle outState) {
         String myValue="SaveValue";
        outState.putStringArrayList("RECOVER", myValue);
         super.onsaveInstanceState();
    }
  • Then the android calls for onDestroy() method, on Create() and onRestoreInstanceState() in a order.
  • Override the onRestoreInstanceState() to recover the saved data in onSaveInstanceState() ,Example
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
    
      String myValue;     
    myValue= savedInstanceState.getStringArrayList("RECOVER"); super.onRestoreInstanceState(savedInstanceState); }
  • This recovers the String named myValue having the content "SaveValue". The keyName which is RECOVER should be unique as it carry the String named myValue(a variable).
More at: https://developer.android.com/guide/topics/resources/runtime-changes.html

No comments:

Post a Comment