Learning this google codelab I faced with such a problem - no state restore, even in solution code I tried few emulators, and live devices with 6 and 9 android versions, but no luck.
Steps I do:
- Open app
- Press "home"
- Call adb command to emulate app kill by system
- Press "recent"
- Choose my app
- In most cases, I see lost state
ADB command used in a codelab: adb shell am kill $APP_PACKAGE_NAME
I found that even I have waited for 10 seconds after "home" before calling ADB command, the state can be lost(in most cases), but if I go after "home" to any other application, and call ADB command after that, in most cases my app can restore state.
The log from the app, where I try to save variable SOME_DATA
I/StateLoose: onCreate hasBundle=false
I/StateLoose: onSaveInstanceState has state: Bundle[{SOME_DATA=Sat Aug 08 17:09:40 GMT+08:00 2020, android:viewHierarchyState=Bundle[{android:views={16908290=android.view.AbsSavedState$1@bb196, 2131165191=androidx.appcompat.widget.Toolbar$SavedState@51a8117, 2131165193=android.view.AbsSavedState$1@bb196, 2131165199=android.view.AbsSavedState$1@bb196, 2131165241=android.view.AbsSavedState$1@bb196}}], android:lastAutofillId=1073741823, android:fragments=android.app.FragmentManagerState@e682904}]
calling adb command, and restoring from recent:
I/StateLoose: onCreate hasBundle=false
The simplified activity code:
const val name: String = "SOME_DATA"
class StateLoose : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_state_loose)
Timber.i("onCreate hasBundle=${null != savedInstanceState}")
savedInstanceState?.run {
Timber.i("data ${getString(name, "")}")
}
}
override fun onSaveInstanceState(outState: Bundle?) {
super.onSaveInstanceState(outState)
outState?.run {
putString(name, Date().toString())
}
Timber.i("onSaveInstanceState has state: $outState")
}
override fun onRestoreInstanceState(savedInstanceState: Bundle?) {
super.onRestoreInstanceState(savedInstanceState)
Timber.i("onRestoreInstanceState ${null != savedInstanceState}")
savedInstanceState?.run {
Timber.i("data ${getString(name, "")}")
}
}
}
So my questions:
- Why the state is lost in some cases?
- How not to lose the state?