In this blog, We are basically going to understand the Activity lifecycle in context of screen rotation. Basically, What do I mean, suppose we are currently in the portrait mode, and in the next step the user tries to rotate the screen, that is, switch to the landscape mode, then
What is the behaviour of the Activity lifecycle methods?
What are the methods that are executed?
And suppose user now wants to switch back to the portrait mode. So again,
What are the lifecycle methods that are executed?
let check it out inside the Android studio.
Checkout master branch of Git Repository:https://github.com/sohamnavadiya/androidlifecycle.git
I have inserted log. This is going to help us to know what are the methods that are executed while we rotate our screen. So let see their behavior.
Log after rotate the screen. You can notice here onPause is executed. onStop is executed, onDestroy is executed. and soon after that onCreate, onStart and on Resume is again executed.
Again rotate screen,
Activity in the landscape mode was destroyed and soon after that the activity starts to create itself in the portrait mode.
On rotation of screen,
- The Activity is Destroyed
- The Activity is Recreated fresh in requested orientation.
Now suppose we are having some views or widgets inside our Activity. So what impact will it hold on our views and variables that are residing inside our Activity?
Let check it out.
Clone following repository, execute the code and rotate device.(Impact of screen)
When we rotate the screen,
Views that DO NOT RETAIN their screen on screen rotation
Views that by default RETAIN their state on screen rotation.
Let’s see possible solution to handle screen Orientation.
Restoring the Activity State
- Activity is destroyed and recreated
- Use onRestoreinstanceState and onSaveinstaceState
Handling configuration change yourself.
- Activity is not destroyed
- Use onConfigurationChanged
- Checkout solution-2 branch of Git Repository.
- In this method, when you switch from Portrait to Landscape, a method is called, onConfigurationChanged method.
- In this method, you need to write your own custom codes to update the resource inside the Activity.
Question: When this method called?
- Declare android:configChanges attribute in Manifest file under
- So after declaring this attribute inside the Manifest file.
- You need to override the onConfigurationChanged method inside the Activity class.
When screen is rotated
- Activity is destroyed
- Activity is recreated in requested orientation
- Views and Variables need to be handled
Restoring the Activity state using onRestoreInstanceState and onSaveInstanceState
- Is generally preferred and recommended
Handling configuration change yourself using on Configration Changed
- Against the guidelines
- Not recommended
- Should be used ONLY when restoring Activity back is expensive and slow.