Static on my Android

This post is mostly to document a pretty tricky little ‘gotcha’ in Android, but I’ll give some background on how I discovered it as well. I’ve been wrestling with a minor bug in MtgHelper lately, mainly for something to do / something to keep me sharp. (RTMg.mob is in a holding pattern at present until Rob has time to tweak the CGI a little.)

Essentially the bug deals with how my two main application modes interact. Normally, MtgHelper operates from an Activity bearing the same name. There is an alternate view mode which operates from the Head2HeadMode Activity which splits the screen and changes how some methods work as a result. In particular, Head to Head ignores orientation changes.

The bug occurs in head to head mode when the user ‘changes orientation’ and then presses the back button. A second copy of the Head2HeadMode activity gets created, so the app gives the illusion of needing to press the Back button twice to get back to the home screen.

I ran into a very interesting snag when trying a solution to correct this bug. I created a static boolean variable (so that I could share it across my two activities without bundling it with my other data). Instead of painstakingly coding the state-saving stuff in the several places it would be needed, I wanted the variable to live and die with the application’s Activities. Interestingly, due to the static variable declaration, the variable was seeming to outlive the application!

As it turns out, even when you use the Back button in Android to completely close an application by taking all of the activities off of the stack, there can still be an Activity process lingering around for a while. This process is every bit as entitled as anything else to have static access to your variable. This results in unpredictable behavior wherein the variable appears to save state sometimes, but may not always. If Android decides to garbage collect my lingering process, the static goes with it.