2

As I understand a singleton cannot be expected to hold persistent data in Android apps because an app may get destroyed and recreated several time in the app's "apparent lifecycle". This in itself is not a problem for me. The problem comes with what exactly happens when an app goes through this destroy -> create process.

I have read on forums that the app will be recreated in a new process, and I assume that the old process with all its memory management will get destroyed. However does this mean that it is up to the developer to clean up all singletons and logical trees with nodes holding mutual references? Or does the destruction of the process automatically cleans up everything? I am not an experienced java developer, so a lot is still unclear to me about the GC.

The specific project I'm working on runs only a single app throughout the uptime of the device. In desktop terms there would be no danger of memory leaks through singletons since the application only shuts down on device shutdown and lives in thesame process the entire time. Android makes it more difficult however.

On a side note, what's a good memory leak detector for Android using the emulator?

Rene
  • 260
  • 2
  • 10
  • 1
    As for memory leak detection tools: Have a look at this Eclipse plugin: http://www.eclipse.org/mat/ and this google io video: https://www.youtube.com/watch?v=_CruQY55HOk – Entreco Mar 24 '13 at 11:07
  • About memory leaks you can also check this answer: http://stackoverflow.com/questions/3714394/how-to-find-memory-leak-class-activity-in-android/14775184#14775184 – rekire Oct 09 '15 at 09:00

1 Answers1

3

Basically you must avoid to keep referenced to UI elements. That UI elements are bound to the context of the activity which could be destroyed.

If you really need a singelton than extend Application class for enforcing that. This instance won't be destroyed when a activity closes, or on rotations and so on.

You should also know that you can handle that events in your code. That means that your activity must not been restarted. IMHO it makes in almost no case sense to restart an Actity. To implement that you need to add the configChanges attribute to your manifest. I personally use this config:

<activity android:configChanges="orientation|screenSize|keyboardHidden" ...>
rekire
  • 47,260
  • 30
  • 167
  • 264
  • thanks for pointing out the Application class! I'll definitely look into that one. However as I read the Android docs, I understood that it is not up to the developer when an activity stops and restarts. The android OS makes that decision for you. – Rene Mar 24 '13 at 11:11
  • well, the original question was whether an activity restart will clean up everything for you, or whether you have to do it yourself. But if your tip leads to a good workaround I'll make your post the correct answer. I have to try it first. – Rene Mar 24 '13 at 11:20