Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my service get instantiated multiple times?

Tags:

android

IIUC, there should only be one instance of a given Android service, it is a singleton.

However, my service gets instantiated multiple times, although I do nothing for it.

When the service crashes (for example when I uninstall the app through adb), it gets scheduled for restart ("Scheduling restart of crashed service.. "). I understand this is an effect of the service being sticky.

After that, when my app starts, it calls startService() and bindService(), and the service gets appropriately started and bound. But the service is then reinstantiated and onCreate() is called repeatedly, as many times it was scheduled for restart.

Each instance then wait for clients to bind and register, but onBind() is only called in the "main" service instance. The additional instances wait a bit for client to bind, and since that doesn't happen, they call stopSelf().

But stopSelf() has absolutely no effect in these "dead" instances, onDestroy() is never called.

The "main" service instance does work as expected, and when it decides to call stopSelf(), onDestroy() is indeed called.

Worse, all these dead instances accumulate, they never gets destroyed. Therefore, their only possible end is a crash (which happen every time I launch/install through adb), and thus scheduled restart.

So that in the end I get many of these dead instances, which are restarted progressively once by minute approximately.

Does anyone know what's going on?

like image 543
olivierg Avatar asked Sep 27 '10 14:09

olivierg


2 Answers

I got similar behavior if I use eclipse to restart an app with a remote service. According to logcat, system consider the killed service had a crash and tried to restart the service. At the same time, the service has been restarted with the restarted app. For some unknown reason, Android system does not realize there is already a running service, and tries to start a new one.

It happens several times on Optimus one, Galaxy tab, and EVO 3D. It is fine with Nexus one.

like image 78
SXC Avatar answered Nov 17 '22 11:11

SXC


Because I haven't seen your code, this is just a guess: Maybe you have a memory leak that prevents the service from destroying properly. That's the only reason I could think of to get multiple instances of service. For example, if you service is holding on to some object that also have a reference to your service. It happens a lot with inner classes.

Check out this video from Google I/O to see if this problem applies to your services and how to find it: http://www.youtube.com/watch?v=_CruQY55HOk&feature=player_embedded

like image 1
Peter Fortuin Avatar answered Nov 17 '22 11:11

Peter Fortuin