Android サービスで、バインドされているクライアントの数を特定する方法はありますか?
3 に答える
サービスにバインドされているクライアントの数を調べる API はありません。
独自のサービスを実装している場合は、ServiceConnection で参照カウントを増減して、バインドされたクライアントの数を追跡できます。
以下は、アイデアを示すための疑似コードです。
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());
}
}
onBind()
(カウントを増やす)、onUnbind()
(カウントを減らして返すtrue
)、 (カウントを増やす)をオーバーライドすることで、接続されているクライアントを追跡できますonRebind()
。
これを行うための簡単で標準的な方法はないようです。2通り考えられます。簡単な方法は次のとおりです。
のようなサービスの API への呼び出しを追加しますdisconnect()
。クライアントは を呼び出すdisconnect()
前に呼び出す必要がありますunbindService()
。private int clientCount
バインドされたクライアントの数を追跡するために、サービスにメンバー変数を作成します。onBind()
でカウントを増やしたり で減らしたりして、バインドされたクライアントの数を追跡しますdisconnect()
。
複雑な方法には、サービスからクライアントへのコールバック インターフェイスを実装し、RemoteCallbackList
実際にバインドされているクライアントの数を決定するために使用することが含まれます。