Michael Gregorov Michael Gregorov - 4 months ago 16
Android Question

Notify an Android service when a bound client disconnects

I have an android service in a remote process that can have multiple bindings from different clients. My question is, how can the service get notified when a specific bound client gets disconnected unexpectedly (i.e the client has crashed)?
I can't use

onUnbind()
, because it only gets called after all clients have been disconnected.

public class MyService extends Service {

final Messenger mServiceMessenger = new Messenger(new IncomingHandler());

@Override
public IBinder onBind(Intent intent) {
return mServiceMessenger.getBinder();
}

@Override
public void onCreate() {
super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_STICKY;
}

class IncomingHandler extends Handler {
@Override
public void handleMessage(Message msg) {
// Handling messages logic...
}
}
}

Answer

you can use the IncomingHandler handler you have and send a message from the client that it will be unbinded before calling unbindService(serviceConnection), keeping arraylist of the Messengers(clients) and add/remove when a message is received.

you can also try to send dummy messages and if you get RemoteException means that the remote client is dead.

check this example http://developer.android.com/reference/android/app/Service.html

extract:

class IncomingHandler extends Handler {
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case MSG_REGISTER_CLIENT:
                mClients.add(msg.replyTo);
                break;
            case MSG_UNREGISTER_CLIENT:
                mClients.remove(msg.replyTo);
                break;
            case MSG_SET_VALUE:
                mValue = msg.arg1;
                for (int i=mClients.size()-1; i>=0; i--) {
                    try {
                        mClients.get(i).send(Message.obtain(null,
                                MSG_SET_VALUE, mValue, 0));
                    } catch (RemoteException e) {
                        // The client is dead.  Remove it from the list;
                        // we are going through the list from back to front
                        // so this is safe to do inside the loop.
                        mClients.remove(i);
                    }
                }
                break;
            default:
                super.handleMessage(msg);
        }
    }
}
Comments