Search code examples
androidrotationrestart

How android restart the activity or fragment on device orientation change?


How does android restart an activity or fragment when rotating the app? I'm interested in the methods or flags it uses in the process. Thx


Solution

  • When any configuration changes, such as device orientation takes place the activity will be destroyed and recreated that is unless you've modified this process inside the manifest file. As @Lazai mentioned, if you change activity configuration changes functionality, you must handle manually loading any new resources required for the new orientation, that includes, styles, themes, drawables, and layouts inside of the callback Activity.onConfigurationChanged(Configuration newConfig).

    Note: if you don't indicate inside of the manifest file that you'd like to manually handle configuration changes, you will never received a call to Activity.onConfigurationChanged(Configuration newConfig).

    Android exports recommend not handling the configuration changes yourself and letting the OS handle itself. So how to know when orientation changes are taking place when you don't get calls to onConfigurationChanged(Configuration newConfig)? Well if you're are targeting above API Level 11, their is a handy method on the Activity class that indicates if activity is experiencing the a configuration change, called Activity.isChangingConfigurations(). This method will always return false until the activity is preparing to be destroyed. It will have a valid value prior to the call Activity.onPause(), that you can check and determine if your device is rotating and your app should perform some special optimizations or state saving procedures.

    I personally recommend letting the system handling the config changes and checking if the orientation is changing, because in a large app or complex activity it can get very tedious reloading the necessary resources and assets just to prevent an activity from discarding a simple object or during rotations.