如何等到服务绑定?

How to wait until service is bound?

我正在为我的应用程序编写蓝牙服务。我对 android 中的服务了解不多,但我设法启动了一个服务并按照我想要的方式使用它。

当我尝试在 Activity 的 onCreate() 方法上使用服务中的函数时,我的问题就在一开始就出现了(它没有足够的时间来绑定服务)。

我将代码结构化为 3 classes:

变量 'isBound' 旨在用于了解服务是否已绑定(或者我们是否必须等待)。

我尝试了什么:

所以我的问题是如何等待 'onCreate()' 方法直到 'isBound' 变为真?

我刚刚意识到我可以在 BluetoothService 上创建两个函数并在 onServiceConnected()onServiceDisconnected() 上调用它们:

private ServiceConnection connection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder binder) {
        BluetoothActivity.this.onServiceConnected(name, (BluetoothService.BluetoothBinder) binder);
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        BluetoothActivity.this.onServiceDisconnected(name);
    }
};

protected void onServiceConnected(ComponentName name, BluetoothService.BluetoothBinder binder){
    bluetoothService = binder.getService();
}

protected void onServiceDisconnected(ComponentName name){
    bluetoothService = null;
}

然后在扩展 class:

上覆盖它们
@Override
protected void onServiceConnected(ComponentName name, BluetoothService.BluetoothBinder binder) {
    super.onServiceConnected(name, binder);
    //TODO
}

@Override
protected void onServiceDisconnected(ComponentName name) {
    // TODO
    super.onServiceDisconnected(name);
}