I have an Android app (activity) which also has a corresponding service. The service is started by the activity and is supposed to run continuously even when the activity is stopped. When the activity is started again it can bind to the service and query it.
Sometimes the activity gets destroyed and created by the OS. This should not affect things, the activity should just be re-created and be able to bind to the service again. This basically works.
However...
I have found that both the Dalvik VM heap and the native heap are non-compacting and therefore constantly increase in size until the activity runs out of memory and crashes (even though the total memory usage is actually constant and not leaking). This is much exacerbated by destroying and re-creating the activity since a lot of allocations are done during the creation process.
This pretty much guarentees that the activity will crash after a number of restarts. This doesn't bother me that much, but what then happens is that the service also crashes because it is part of the same application. The service contains some important data which is then lost during the crash.
I am interested in any suggestions as to how to solve this problem?
Is there a way to separate the service from the activity (so that when the activity crashes it won't also crash the service), yet still have the service and the activity in the same application?
I could persist the service data but this would require many accesses to a DB and is not that conducive to saving battery.
It sounds like your service is maintaining references to your defunct activities. You should be using a started service, not a bound service. See the guide topic on Services for details about the differences and how to use each one.
ReplyDeleteIf you want to use a bound service (that is, you really need to use bindService() for some reason), then be sure to call unbindService() before your activity dies. Note that when the last activity unbinds, the service is halted.