Singleton is destroyed

I have an activity that starts a service. The singleton Data also involved. When I close the activity by going to the desktop, the singleton Data destroyed after a while, but, as it should be, the service continues to work. Therefore, some Data fields become null again, and the service encounters null pointers.

How can I prevent this?

+4
source share
2 answers

As far as I know, Activity instances run in their own class loader for security. Any singleton attached to a class that loads as a result of loading your Activity is tied to this classloader, which in turn is tied to the activity life cycle.

That is, I do not think that you can guarantee that this will not happen, and therefore you should not rely on it.

You need to serialize some kind of persistent state, and then unserialize when the Activity starts.

+6
source

One way to achieve this is to keep a reference to your object in your subclass of the created Application . This is a simple solution that works in most cases without having to create a Service or to serialize the state all the time.

+1
source

All Articles