How to simulate killing activity to conserve memory? How to simulate killing activity to conserve memory? android android

How to simulate killing activity to conserve memory?


You can't do it in an automated way b/c its completely non deterministic.

See my answer here: https://stackoverflow.com/a/15048112/909956 for details.

But good news is that all you need to do is just simulate calling onSaveInstanceState and you are indirectly testing this low memory situation.

onSaveInstanceState can be triggered by:

  1. losing focus (by pressing home which in essence is like switching from your app to launcher app), launching another activity, pressing recents
  2. changing orientation. this is the easier way if you are using an emulator
  3. changing developer setting: goto developer options --> Apps --> Don't keep activities. This is best option if you are testing temporarily on an actual device.


I've used the "Don't keep activities" developer option to reproduce a crash that happened when an activity was killed due to memory pressure. You can find it in the Apps section of Settings->Developer Options.

It destroys every activity as soon as you leave it. E.g. if you press home to put your app in the background the current activity is destroyed. See https://stackoverflow.com/a/22402360/2833126 for more information.


There's two way to simulate the android killing process: using the setting "Don't keep activities" in developer settings or killing the app process by yourself.

To kill the process, open the activity you want to test, then press home button to send your app to background, and then, using the DDMS in Android Studio (Android Device Monitor), select the process and then stop the process (as seen in the image below). Your app was killed. Now, open your app again (accessing the list of open apps). Now you can test the killed state.

enter image description here