2012-08-07 89 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

相關問題