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?

有帮助吗?

解决方案

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" ...>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top