Best practices while handling android application lifecycle.
Saving Instances of Android App
- onSaveInstanceState is a callback where you could save data that you might need in case the Android OS destroys your app.
- onSaveInstanceState is called after the app goes in state onStop (Note* after API 28 )
- Best practice to keep this data in Bundle small while we save, generally we should store maximum of 100 KB otherwise the app will crash.
Use Case:
- save required data in onSaveInstanceSate bundle as key_value pair
- recover the data in onRestoreInstanceState or onCreate with it's bundle
- Change the orientation of screen and check if the saved instance works
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState!= null){
amount = savedInstanceState.getInt(AMOUNT_KEY)
}
}
override fun onStop() {
super.onStop()
Timber.i("onStop called")
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putInt(AMOUNT_KEY, amount)
Timber.i("onSaveInstanceState called")
}
Note that : onRestoreInstanceState is called after onStart
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
}
Comments
Post a Comment