【发布时间】:2017-09-07 17:20:24
【问题描述】:
我是 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
【问题讨论】:
-
外设的广告间隔是多少?
-
我是 BT 新手,希望我的回答有意义。按下 AT 指令 AT+ADVI 后? ,我得到一个值 0(对应于 100 毫秒),经过进一步研究,我发现这是我目前使用的 HMSoft 模块的默认值。更改此号码会帮助我更快地连接吗?
-
当然。广告间隔与连接建立时间直接相关。
-
查看数据表,我看到我的模块可以有100ms - 7000ms之间的广告间隔。正如我已经提到的,我的时间是 100 毫秒。是否有一定的范围可以产生最好的结果,或者我只需要尝试值,看看什么效果最好?
标签: android bluetooth bluetooth-lowenergy bluetooth-gatt