10 September 2015

Raising Activities From the Dead

One of the scenarios I admittedly almost always forget to test is "What happens when my app goes into the background, then the OS kills is to claim memory, then I try to resume?" Usually it's "Well, I handle onSavedInstanceState not being null, so I am great!" It is fine and dandy for simple apps; but once your Activity or Fragment gets beefier and you start relying on state for more and more things, it can get complicated pretty quickly (In my case, the Fragment has setRetainInstance(true)).

This scenario in particular is kind of hard to reproduce willingly. I usually see this when I leave an app running, make my phone do some heavy work overnight, then resume the app the next day.

So what you gonna do?

It turns out that Android Studio has the answer! There is this magical tiny red button that allows you to simulate this exact scenario.

1. Open your app to the Activity you want to test (I use a very simple app here just for demo).

2. In Studio, go to Android Monitor (make sure that your app is selected). Note the process ID, in this case it is 25647.

3. Push your app to the background. Pressing the HOME button should be sufficient. This will call onSaveInstanceState, which is all that matters really. It is after all what we want to test.

4. Back in Studio, press the magical tiny red button pointed to in the previous image. Notice that Studio now appends [DEAD] to your app's process. It is now gone. He's dead, Jim!

5. Resume your app. I usually just do this via recent apps.

6. If you look at Studio, you'll see that your app is now no longer dead, but has a new process ID, in this case 26742.

If at this point you step through your code, you will notice that your Activity will go through the whole (re-)creation process with the Bundle given the values you have saved in onSaveInstanceState. No more waiting overnight, yay!