zer0stimulus
zer0stimulus

Reputation: 23666

Android: How to determine how many clients are bound to a service?

In an Android service, is there a way to determine how many clients are bound to it?

Upvotes: 9

Views: 3676

Answers (3)

jonasb
jonasb

Reputation: 1875

You can keep track of the connected clients by overriding onBind() (increase count), onUnbind() (decrease count and return true) and onRebind() (increase count).

Upvotes: -1

David Wasser
David Wasser

Reputation: 95626

There doesn't seem to be an easy, standard way to do this. I can think of 2 ways. Here's the simple way:

Add a call to your service's API like disconnect(). The client should call disconnect() before it calls unbindService(). Create a member variable in the service like private int clientCount to keep track of the number of bound clients. Track the number of bound clients by incrementing the count in onBind() and decrementing it in disconnect().

The complicated way involves implementing a callback interface from your service to the clients and using RemoteCallbackList to determine how many clients are actually bound.

Upvotes: 0

Akos Cz
Akos Cz

Reputation: 12790

There's no API to find out how many clients are bound to a Service.
If you are implementing your own service, then in your ServiceConnection you can increment/decrement a reference count to keep track of the number of bound clients.

Following is some psudo code to demonstrate the idea :

MyService extends Service {

   ...

   private static int sNumBoundClients = 0;

   public static void clientConnected() {
      sNumBoundClients++;
   }

   public static void clientDisconnected() {
      sNumBoundClients--;
   }

   public static int getNumberOfBoundClients() {
      return sNumBoundClients;
   }
}

MyServiceConnection extends ServiceConnection {

    // Called when the connection with the service is established
    public void onServiceConnected(ComponentName className, IBinder service) {
        ...
        MyService.clientConnected();
        Log.d("MyServiceConnection", "Client Connected!   clients = " + MyService.getNumberOfBoundClients());
    }

    // Called when the connection with the service disconnects
    public void onServiceDisconnected(ComponentName className) {
        ...
        MyService.clientDisconnected();
        Log.d("MyServiceConnection", "Client disconnected!   clients = " + MyService.getNumberOfBoundClients());
    }
}

Upvotes: 6

Related Questions