Screen Rotation Question


I noticed that when I make changes to the Crime data it is resistant to rotations of the screen, and wanted to confirm that I understand why this is happening.

  1. Because CrimeLab is a singleton its class data which includes the mCrimes arraylist stays as long as the application is loaded in memory. So even though the activities are being taken down (Destroy) and rebuilt (Create), the application’s context is still in place so the singleton data is preserved across rotations.

  2. I also tried rotating while in the fragment, and this too resists rotations because as the Listeners (for text activity and checkbox activity) are called when the user interface of the fragment is utilized, they store the change into the CrimeLab mCrimes structure immediately, so for the same reason (singleton) there are no issues for rotation change etc.

Just wanted to confirm this - if this is indeed the case when would the application’s context actually go away (and your singleton data)?


You are correct on both counts. This is something that I’ve only lately realized about our coverage - the techniques we use in CriminalIntent solve a lot of rotation pain, but we never talk about how awesome that is. We think that tactics like that are the key to staying sane as an Android dev.

As to when the singleton would be destroyed - well, it would be destroyed whenever the process is destroyed. You have no real control over when this happens, unfortunately. What we can say for sure is:

  1. If your activity is in the foreground, your process almost certainly will not die.
  2. If you don’t have any live application components (activities, services, receivers), your process will almost certainly be killed.