android
activity-restart
screen-rotation
mobile-development
android-lifecycle

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 development, handling Activity restarts upon device rotation is essential to maintain a consistent user experience. When an Android device's orientation changes (e.g., from portrait to landscape), the system destroys and recreates the Activity by default. This process can lead to data loss and performance issues if not managed correctly. Let's explore the technicalities, methods, and practices to handle these situations effectively.

Activity Life Cycle

Before delving into details about handling Activity restarts, it's pertinent to understand the Android Activity lifecycle. Upon an orientation change, an Activity undergoes a sequence of lifecycle callbacks:

  1. onPause(): Invoked when the Activity is partially obscured.
  2. onStop(): Called when the Activity is no longer visible.
  3. onDestroy(): The Activity is destroyed.
  4. onCreate(): The Activity is recreated.
  5. onStart(): The Activity becomes visible.
  6. onResume(): The Activity gains focus.

By default, rotation triggers a full restart of the Activity. However, various strategies can be employed to mitigate potential issues associated with this behavior.

Strategies to Handle Rotation

Saving Instance State

One of the most technique approaches to preserve UI states during rotation is by utilizing the onSaveInstanceState() and onRestoreInstanceState() callbacks.

  • onSaveInstanceState(Bundle outState): This method is invoked before an Activity is destroyed, allowing developers to save key-value pairs (Bundle) representing the current state. For example, saving the text in a TextView:
java
1  @Override
2  protected void onSaveInstanceState(Bundle outState) {
3      super.onSaveInstanceState(outState);
4      outState.putString("KEY_TEXT", editText.getText().toString());
5  }
  • onRestoreInstanceState(Bundle savedInstanceState): Called after onStart() if the Activity is being recreated, use this method to restore the saved state:
java
1  @Override
2  protected void onRestoreInstanceState(Bundle savedInstanceState) {
3      super.onRestoreInstanceState(savedInstanceState);
4      String savedText = savedInstanceState.getString("KEY_TEXT");
5      editText.setText(savedText);
6  }

Configuring in Manifest

Another approach to handle configuration changes, like rotation, without restarting the Activity is by modifying the AndroidManifest.xml:

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

By doing this, you override the default behavior, and the system calls onConfigurationChanged(Configuration newConfig) instead of destroying and recreating the Activity.

ViewModel Persistence

For more complex data that require persistence beyond configuration changes, consider using the Android Architecture Components' ViewModel. ViewModel instances survive configuration changes:

java
1public class MyViewModel extends ViewModel {
2    private MutableLiveData<String> data;
3    
4    public MutableLiveData<String> getData() {
5        if (data == null) {
6            data = new MutableLiveData<String>();
7        }
8        return data;
9    }
10}

The ViewModel retains UI-related data and is scoped to a component lifecycle, preserving data during recreation.

Ensuring Smooth Transitions

Using the appropriate mechanisms to manage Activity restarts during rotation can significantly improve user experience. It is crucial to be aware that each method has its tradeoffs and is suitable for distinct scenarios.

Key Points Summary

Concept/MethodDescriptionUse Case
Activity LifecycleSeries of callbacks during Activity state transitions.Understanding the process when Activity restarts.
onSaveInstanceState/onRestoreInstanceStateSave and restore UI states using a Bundle.Simple UI data preservation.
Android Manifest ConfigurationPrevents Activity restarts by handling specific changes in onConfigurationChanged().For Activities that manage configuration changes manually.
ViewModelArchitecture component that retains UI-related data throughout configuration changes.Complex data management during configuration changes.

Conclusion

Handling Activity restarts on device rotation involves understanding the Android lifecycle and employing appropriate strategies. Whether using onSaveInstanceState(), configuration changes in the manifest, or ViewModel, each method provides mechanisms to preserve UI states across configuration changes, enhancing user experience and application reliability. Each approach has particular advantages and tradeoffs, thus selecting the right one depends on the specific app requirements and the complexity of the data being handled.


Course illustration
Course illustration

All Rights Reserved.