我是 android BLE 开发和一般 BLE 开发的新手,我注意到大多数情况下,Android 可能需要 3-7 秒才能在我的 connectGatt 调用之后触发对 onConnectionStateChange 的调用。这是正常的吗?我很好奇,因为我之前使用过蓝牙 2.0,那里的一切都快得多。此外,我在 iPhone 上进行了一些测试编码,初始连接的建立也更快。我将在下面发布一个示例代码以及一些指示减速发生的位置的 android 监视器消息。
class BluetoothConnection{
void connectToDevice(BluetoothDevice device) {
if (mBluetoothGatt == null) {
Log.d(TAG, "-----Trying to connect to GATT server.");
mBluetoothGatt = device.connectGatt(mContext, false, mGattCallback);
}
}
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
if (newState == BluetoothProfile.STATE_CONNECTED) {
Log.d(TAG, "-----Connected to GATT server.");
Log.d(TAG, "-----Attempting to start service discovery:" +
mBluetoothGatt.discoverServices());
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
Log.d(TAG, "-----Disconnected from GATT server.");
}
}
@Override
// New services discovered
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
Log.w(TAG, "-----Successfully discovered the services");
BluetoothGattService gattService = mBluetoothGatt.getService(UUID.fromString("0000ffe0-0000-1000-8000-00805f9b34fb"));
Log.d(TAG, "-- Service = " + gattService.getUuid());
characteristicsTxRx = gattService.getCharacteristic(UUID.fromString("0000ffe1-0000-1000-8000-00805f9b34fb"));
Log.d(TAG, "-- Characteristic = " + characteristicsTxRx.getUuid());
mBluetoothGatt.setCharacteristicNotification(characteristicsTxRx, true);
Intent intent = new Intent(CONNECTION_ESTABLISHED);
mContext.sendBroadcast(intent);
}
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
super.onCharacteristicChanged(gatt, characteristic);
final byte[] data = characteristic.getValue();
if (data != null && data.length > 0) {
Intent intent = new Intent(DATA_AVAILABLE);
String incomingMessage = new String(data);
intent.putExtra(DATA, incomingMessage);
mContext.sendBroadcast(intent);
}
}
};
}
这里有几行来自我的日志,你可以看到这里花了将近 5 秒来确认我们已连接到 GATT。
09-07 10:07:05.211 29907-29907/com.bubblewall.saik.bubblewall D/bubbleWallMessage: -----Trying to connect to GATT server.
09-07 10:07:09.898 29907-29920/com.bubblewall.saik.bubblewall D/bubbleWallMessage: -----Connected to GATT server.
09-07 10:07:09.901 29907-29920/com.bubblewall.saik.bubblewall D/bubbleWallMessage: -----Attempting to start service discovery:true
09-07 10:07:10.347 29907-29920/com.bubblewall.saik.bubblewall W/bubbleWallMessage: -----Successfully discovered the services