How to test code built to save/restore Lifecycle of an Activity?
AndroidAndroid ActivityLifecycleAndroid Problem Overview
How can I test all of the following methods code? I want to play scenarios when all of them are happening to see if my code works for save/restore process of an activity. So what should I do in the Emulator to get all methods tested?
public class Activity extends ApplicationContext {
protected void onCreate(Bundle savedInstanceState);
protected void onStart();
protected void onRestoreInstanceState(Bundle savedInstanceState);
protected void onSaveInstanceState(Bundle savedInstanceState);
protected void onRestart();
protected void onResume();
protected void onPause();
protected void onStop();
protected void onDestroy();
}
Android Solutions
Solution 1 - Android
If you have enabled Developer Options on your device, there is an option Do not keep activities that will help test onRestoreInstanceState()
.
Solution 2 - Android
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).
Solution 3 - Android
To test onSaveInstanceState and onRestoreInstanceState you can use either the SetAlwaysFinish tool (see link below) or the DevTools app included with the emulator.
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.
Solution 4 - Android
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.
Solution 5 - Android
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)
}
}