2012-08-07 82 views

回答

4

有没有API来找出有多少客户端绑定到服务。
如果您正在实施自己的服务,那么在ServiceConnection中,您可以递增/递减引用计数以跟踪绑定客户端的数量。

以下是一些psudo代码验证这个想法:

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()); 
    } 
} 
+0

+1但是,如果你在同一进程中的客户端上运行的本地服务这仅适用。如果您的服务在远程进程中运行,则它不起作用,如果您向不属于您的应用程序的多个客户端提供服务,它也不起作用。 – 2012-08-07 18:27:23

+0

David是对的,我的示例只适用于本地服务。 – 2012-08-08 00:44:42

+0

我还没有实现RemoteService的需要,所以我不确定RemoteCallback列表如何用于使我的示例与RemoteService一起工作。 – 2012-08-08 00:53:40

0

似乎有不被这样做一个简单的,标准的方式。我可以想到2种方法。下面是简单的方法:

添加调用服务的API像disconnect()。客户应在拨打unbindService()之前致电disconnect()。在服务中创建一个成员变量,如private int clientCount以跟踪绑定客户端的数量。通过递增onBind()中的计数并在disconnect()中递减计数来跟踪绑定客户端的数量。

的复杂的方式包括从服务到客户端实现的回调接口,并使用RemoteCallbackList,以确定有多少客户实际的约束。

0

您可以通过覆盖onBind()(增加计数),onUnbind()跟踪所连接的客户端(减计数和返回true)和onRebind()(增加数)。

+0

根据[此](https://groups.google.com/forum/#!msg/android-developers/2IegSgtGxyE/iXP3lBCH5SsJ),'onBind()'对第一请求和缓存'IBinder'调用一次由系统在后续请求中返回而不会影响服务。有关此问题的文档不正确。 – Daniel 2015-02-12 16:13:15

相关问题