android 蓝牙 断开连接和取消配对的广播
时间: 2023-07-30 17:10:33 浏览: 219
在 Android 中,断开连接和取消配对的广播分别是 ACTION_ACL_DISCONNECTED 和 ACTION_BOND_STATE_CHANGED。
ACTION_ACL_DISCONNECTED 广播在 BluetoothAdapter 中定义,当蓝牙连接断开时发送。您可以使用以下代码注册和接收此广播:
```
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_ACL_DISCONNECTED.equals(action)) {
// 处理断开连接的逻辑
}
}
};
IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_ACL_DISCONNECTED);
registerReceiver(mReceiver, filter);
```
ACTION_BOND_STATE_CHANGED 广播在 BluetoothDevice 中定义,当蓝牙设备配对状态更改时发送。您可以使用以下代码注册和接收此广播:
```
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
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);
int bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
int previousBondState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR);
if (bondState == BluetoothDevice.BOND_NONE && previousBondState == BluetoothDevice.BOND_BONDED) {
// 处理取消配对的逻辑
}
}
}
};
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(mReceiver, filter);
```
阅读全文