Android Development
Screen Rotation
Activity Lifecycle
App Development
Android UI

Activity restart on rotation Android

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

In Android, handling configuration changes like screen rotation is crucial for maintaining a smooth and seamless user experience. When a device's screen is rotated, Android typically restarts the currently running activity to adapt to the new orientation by default. In this article, we will dive deep into this behavior, discuss its implications, how to manage it, and when to leverage it for better application performance.

Understanding Activity Lifecycle on Rotation

When an Android device's screen orientation changes (from portrait to landscape or vice-versa), the Activity undergoes a restart process. This is primarily because the change in orientation can require different resource layouts (like XML files in res/layout-land and res/layout-port directories).

The Lifecycle Process

Here’s what happens under the hood when a screen rotation occurs:

  1. onPause(): This method is called as the first indication that the user is leaving the activity.
  2. onStop(): The activity is no longer visible.
  3. onDestroy(): The system destroys the activity. At this point, the activity is cleaned up, and state and member information are lost unless saved and restored.
  4. onCreate(): The activity is created again with the new orientation.
  5. onStart(): The activity becomes visible again.
  6. onResume(): The user begins interacting with the activity.

Handling Orientation Changes

To manage an orientation change, you typically have two options: let Android handle it by restarting the activity, or handle it yourself by specifying configurations in the manifest.

Letting Android Handle Configuration Changes

By default, Android handles rotation by saving instance states and restoring them. For complex UIs or heavy resources, this might not be efficient. The onSaveInstanceState() and onRestoreInstanceState() callbacks allow you to save and restore state during orientation changes.

Example:

java
1@Override
2protected void onSaveInstanceState(Bundle outState) {
3    super.onSaveInstanceState(outState);
4    outState.putString("myStateKey", "stateValue");
5}
6
7@Override
8protected void onRestoreInstanceState(Bundle savedInstanceState) {
9    super.onRestoreInstanceState(savedInstanceState);
10    String stateValue = savedInstanceState.getString("myStateKey");
11}

Handling Configuration Changes Manually

If you decide to handle the rotation yourself, you need to declare it in your activity’s AndroidManifest.xml file by adding the android:configChanges attribute to the <activity> tag.

Example:

xml
<activity android:name=".MainActivity"
          android:configChanges="orientation|screenSize">
</activity>

By doing this, instead of destroying and recreating the activity, Android calls the onConfigurationChanged() callback, where you can handle what changes when the orientation switches.

Example in code:

java
1@Override
2public void onConfigurationChanged(Configuration newConfig) {
3    super.onConfigurationChanged(newConfig);
4    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
5        // Code to adjust UI for landscape mode
6    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
7        // Code to adjust UI for portrait mode
8    }
9}

Performance Implications

Handling orientation changes efficiently is key to maintaining performance and user experience. Instantiating complex views or data within methods like onCreate() can slow down the response to a configuration change. Using lightweight fragments, asynchronous loading, and maintaining a separation of concerns are good practices to optimize orientation changes.

Best Practices

  • Maintain responsiveness: Use Loader or asynchronously load data to prevent UI thread block.
  • Minimize Critical Data Loss: Use ViewModel to store UI-related data that isn't affected by lifecycle changes.
  • Testing: Ensure that both orientations produce the expected results.

Summary Table

MethodDescriptionWhen to Use
onSaveInstanceStateSave activity data stateData needs to be retained on config changes
onRestoreInstanceStateRestore activity data from saved stateAfter onStart() when data needs restoring
onConfigurationChangedHandle changes without restarting activityConfigChanges attribute is set in manifest

Conclusion

Understanding and managing activity restarts due to orientation changes in Android is vital for crafting robust and user-friendly applications. By choosing the appropriate method for handling these restarts, developers can greatly enhance the application's performance and user experience. Whether through automated state saving and restoration or manual configuration handling, knowing how and when to use these tools is key to developing proficient Android applications.


Course illustration
Course illustration

All Rights Reserved.