Android: How to determine how many customers are associated with the service?

Is there a way in Android to determine how many clients are tied to it?

+5
source share
3 answers

There is no API to find out how many customers are associated with the Service.
If you are implementing your own service, then in your ServiceConnection you can increase / decrease the reference counter to track the number of connected clients.

Below 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());
    }
}
+4
source

This seems to be a simple, standard way to do this. I can think of two ways. Here is an easy way:

API, disconnect(). disconnect(), unbindService(). - , private int clientCount, . , onBind() disconnect().

RemoteCallbackList, , .

0

, onBind() ( ), onUnbind() ( true) onRebind() ( ).

0