Sobes.tech
Junior

Why does activity recreation occur when rotating the screen?

sobes.tech AI

Answer from AI

When the screen orientation changes, the device configuration changes, for example, orientation. Android responds to this by destroying and then recreating the activity to apply necessary changes in resources, such as layout files specific to portrait or landscape orientation.

Lifecycle of an activity during a rotation:

  1. onPause()
  2. onStop()
  3. onDestroy()
  4. The system creates a new instance of the activity.
  5. onCreate()
  6. onStart()
  7. onResume()

To save state data before the activity is destroyed, use:

  • onSaveInstanceState(): saves small data in a Bundle.

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putString("myKey", "myValue") // Save data
    }
    

    Restoration in onCreate() or onRestoreInstanceState():

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // ...
        if (savedInstanceState != null) {
            val myValue = savedInstanceState.getString("myKey") // Restore data
        }
        // ...
    }
    
  • ViewModel: Stores data throughout the lifecycle of the UI controller (Activity/Fragment), even when configuration changes. ViewModel survives activity destruction and does not lose its state.

    class MyViewModel : ViewModel() {
        var counter = 0
    }
    

    Usage in activity/fragment:

    class MyActivity : AppCompatActivity() {
        private lateinit var viewModel: MyViewModel
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            viewModel = ViewModelProvider(this).get(MyViewModel::class.java)
            // Now viewModel.counter persists during rotation
        }
    }
    
  • Saving data in SharedPreferences or a database for more persistent data.

To prevent activity recreation during screen rotation, you can declare that the activity handles configuration changes itself. This is done in the manifest by adding the configChanges="orientation|screenSize|screenLayout" attribute to the <activity> tag:

<activity android:name=".MyActivity"
          android:configChanges="orientation|screenSize|screenLayout">
</activity>

In this case, instead of being recreated, the onConfigurationChanged() method will be called:

override fun onConfigurationChanged(newConfig: Configuration) {
    super.onConfigurationChanged(newConfig)
    // Handle configuration change manually
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        // Logic for landscape orientation
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        // Logic for portrait orientation
    }
}

Using configChanges is not recommended in most cases, as it can lead to complexities in managing state and resources during various configuration changes. The preferred approach is to use ViewModel for saving state data.

Why does activity recreation occur when rotating the… - sobes.tech