问题描述:在使用Bluetooth Low Energy通信时,无法调用BluetoothGattCallback onConnectionStateChanged()方法。
解决方案:在连接状态改变时手动调用BluetoothGattCallback onConnectionStateChanged()方法。
示例代码:
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
if (newState == BluetoothProfile.STATE_CONNECTED) {
mConnectionState = STATE_CONNECTED;
mHandler.sendEmptyMessage(MSG_STATE_CONNECTED);
gatt.discoverServices();
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
mConnectionState = STATE_DISCONNECTED;
mHandler.sendEmptyMessage(MSG_STATE_DISCONNECTED);
} else if (newState == BluetoothProfile.STATE_CONNECTING) {
mConnectionState = STATE_CONNECTING;
mHandler.sendEmptyMessage(MSG_STATE_CONNECTING);
} else if (newState == BluetoothProfile.STATE_DISCONNECTING) {
mConnectionState = STATE_DISCONNECTING;
mHandler.sendEmptyMessage(MSG_STATE_DISCONNECTING);
}
}
};
private void manuallyInvokeOnConnectionStateChange(int newState){
mGattCallback.onConnectionStateChange(mBluetoothGatt, null, newState);
}
由于BluetoothGattCallback onConnectionStateChanged()方法在连接状态改变时并不总是会被自动调用,我们可以手动调用该方法以确保其被调用。以上代码中的manuallyInvokeOnConnectionStateChange方法即可手动调用BluetoothGattCallback onConnectionStateChanged()方法。