My app uses a pattern where I start a service with Context#startService() as well as bind to it with Context#bindService(). This is so that I can control the lifetime of the se
I believe the problem here is that for a Service that was started by calling startService()
, the internal accounting for its bindings (affected by calls to bindService()
/unbindService()
) are somehow preventing the service to be brought down correctly after it is scheduled for restart when the process is killed.
Depending on your preference, it seems that there are three alternatives to avoid this issue (you mentioned the first two already in your question):
Use startService()
/stopService()
only, do not use bindService()
/unbindService()
at all.
Use bindService()
/unbindService()
only (with BIND_AUTO_CREATE
), do not use startService()
/stopService()
at all.
If you need startService()
/stopService()
and bindService()
/unbindService()
, override the onUnbind() method in your service and call stopSelf()
from it:
@Override
public boolean onUnbind(Intent intent) {
stopSelf();
return super.onUnbind(intent);
}
From my testing:
Using the first alternative will print this line in the log:
W/ActivityManager( nnn): Scheduling restart of crashed service xxxx in 5000ms
but the service will not be really restarted after that.
The second alternative will cause your service to be destroyed after you unbind (in the Activity's onStop()
in your example).
The third alternative will basically make your code behave like the second alternative (without needing to change it by much).
Hope this helps!