How to test code built to save/restore Lifecycle of an Activity?
If you have enabled Developer Options on your device, there is an option Do not keep activities that will help test onRestoreInstanceState()
.
We had an issue whereby re-launching an app after long periods of inactivity crashed. We found that "Don't keep activities" wasn't reproducing the issue, but Background process settings :: No background processes
in Dev Settings did (even while debugging).
To test onSaveInstanceState and onRestoreInstanceState you can use either the SetAlwaysFinish tool (see link below) or the DevTools app included with the emulator.
http://bricolsoftconsulting.com/how-to-test-onsaveinstancestate-and-onrestoreinstancestate-on-a-real-device/
Both of these apps use a hidden setting called AlwaysFinish which is part of the ActivityManagerNative class to change the behavior of the Android OS. Under the new behavior, the OS will unload any activity as soon as it leaves the screen, triggering the onSaveInstanceState event. When the OS wants to bring the activity back, it will call the onRestoreInstanceState event.
The link above explains how to use the SetAlwaysFinish app to test your app's onSaveInstanceState and onRestoreInstanceState events. If you want to use the DevTools, then enable Development Settings > Immediately destroy activities.
There is another way to test these events. First you have to navigate to the specific Activity that you wanna test, then press the home button and go to the Android device monitor.
In this tool you can select a thread of the Application and kill it with the stop button. For last, you have to open the app from the history and the thread will be recreated again.
The testing tools offered by Android now offer a means of writing tests that can drive an activity from one state to another, or to recreate an activity to test the save and restore flow. See the Test your app's activities Android Developers documentation page for a list of the capabilities. An example of the syntax – taken from that page – is the following:
@RunWith(AndroidJUnit4::class)
class MyTestSuite {
@Test fun testEvent() {
val scenario = launchActivity<MyActivity>()
scenario.moveToState(State.CREATED)
}
}