I would like to ask for a help with this issue. It looks like quite common scenario but I didn't found an answer anywhere. It is only mentioned here
I have one service A that is bound to second service B using service connection C.
- A is running and bound to B
- B is stopped and destroyed (no error state - it normally finishes)
- onServiceDisconnected() is called on C
- I have found some mentions about this that it is not called normally. But I can observe it when B is destroyed.
- What should I do with C now?
- According guide, I should do nothing (because B is destroyed and disconnected). But this leads to service leak exception when A is destroyed because C is still active!
So my question is: Where is the bug? In my scenario or in Google's guide.
I tried to change the code in A to following form and it looks that it works well, but it is ugly:
private final ServiceConnection mServiceConnection = new ServiceConnection()
{
boolean bound = false;
@Override
public void onServiceDisconnected(ComponentName name)
{
mService = null;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service)
{
mService = ((MyService.ServiceBinder) service).getService();
if (!bound)
{
// do some action - service is bound for the first time
bound = true;
}
}
};
@Override
public void onDestroy()
{
if (mService != null)
{
// do some finalization with mService
}
if (mServiceConnection.bound)
{
mServiceConnection.bound = false;
unbindService(mServiceConnection);
}
super.onDestroy();
}
public void someMethod()
{
if (mService != null)
{
// I have to test mService, not mServiceConnection.bound
}
}
Is there any other option how to handle it correctly? Thank You very much for help or opinion.