Android, unbind service and onServiceDisconnected problem

UAS picture UAS · Mar 13, 2011 · Viewed 18.6k times · Source

I'm not good in English, but I would try to explain my problem in good way.

So, the problem is:
1) I have a local service
2) I start it and then bound to it. 3) Problem appears when I am about to close that service. onServiceDisconnected method from my implementation of class ServiceConnection is never called. If I close it manually (from settings), or by unbindService, or by stopService, or by combination of unbindService and stopService - onServiceDisconnected still doesn't to be called. What am I doing wrong?

Short code is below:

protected ServiceConnection mServerConn = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder binder) {
        Log.d(LOG_TAG, "onServiceConnected");
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        Log.d(LOG_TAG, "onServiceDisconnected");
    }
}

public void start() {
    // mContext is defined upper in code, I think it is not necessary to explain what is it 
    mContext.bindService(i, mServerConn, Context.BIND_AUTO_CREATE);
    mContext.startService(i);
}

public void stop() {
    mContext.stopService(new Intent(mContext, ServiceRemote.class));
    mContext.unbindService(mServerConn);
}

I'm testing this code under emulator of Android 2.2

Answer

darma picture darma · Mar 13, 2011

onServiceDisconnected is only called in extreme situations (crashed / killed).

which is very unlikely to happen for a local service since all your application components normally run in the same process... meaning, unless you intentionnaly unbind or destroy the service, it should remain connected, or die with the component using it.