Simulate killing of activity in emulator Simulate killing of activity in emulator android android

Simulate killing of activity in emulator


You can pause your application (by pushing the Home button, simulating a call, whatever). Then kill the app's process through adb. Since the docs say that after onPause() returns your app can be killed without any further notice, this is a fair test.

If you don't want to go through the trouble of finding the pid of your app's process, you can use adb shell am kill com.example.package_name to kill your app's process. Make sure that the app is put in the background. The docs say that this command "kills only processes that are safe to kill and that will not impact the user experience." So you might want to launch a couple of other apps before trying this one.


To test the onSaveInstanceState and onRestoreInstanceState events you can use the SetAlwaysFinish utility (see link below). It uses a hidden system setting called Always Finish to change the behavior of the Android system. With the Always Finish option enabled, the Android OS will immediately unload any activity that moves from the foreground to the background, triggering its onSaveInstanceState event. Then, when the system needs the activity again, it is forced to reload it triggering the onRestoreInstanceState event.

The advantage of this method compared to killing the process is that it's easier and you get finer control (activity level rather than process level).

See the blog post below for more details on the tool and how to use it:http://bricolsoftconsulting.com/how-to-test-onsaveinstancestate-and-onrestoreinstancestate-on-a-real-device/

The Always Finish feature is also present in the emulator in the DevTools app under Development Settings > Immediately destroy activities. However, the DevTools app does not work outside of the emulator.


There's a more solid solution for this in Android 6 and newer. I've used the following method successfully on Android 6, 7, and 8:

1) Open your app, go to the activity that you want to test restoring, and then leave it by pressing the Home button

2) Open the Settings app, go to System -> Developer Options, then tap on "Running Services"

3) Tap on "Show Cached Processes" at the top right, then find your app in the list, tap on it, and then tap the "Stop" button.

4) Use the recent apps list to return to your app. It should relaunch the whole app on the activity that you had previously left it from.

I've found this to be sufficient to fully kill the app, including any app delegate stuff and the C/C++ native code state, and then test relaunching it with a saved activity state... This effectively replicates what happens when the user leaves the app for a while and then the system kills it to save memory, battery, or whatever.