Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

android

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

like image 331
zer0stimulus Avatar asked Aug 07 '12 15:08

zer0stimulus


1 Answers

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());
    }
}
like image 56
Akos Cz Avatar answered Nov 15 '22 01:11

Akos Cz