我找到了解决方案 .
首先,我需要 BroadcastReceiver 喜欢:
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
// CONNECT
}
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Discover new device
}
}
};
然后我需要注册接收器如下:
IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
context.registerReceiver(myReceiver, intentFilter);
通过这种方式,接收器正在监听 ACTION_FOUND (发现新设备)和 ACTION_BOND_STATE_CHANGED (设备更改其绑定状态),然后我检查新状态是否为 BOND_BOUNDED 以及是否我与设备连接 .
现在,当我调用 createBond 方法(在问题中描述)并输入引脚时, ACTION_BOND_STATE_CHANGED 将触发, device.getBondState() == BluetoothDevice.BOND_BONDED 将为 True ,它将连接 .