我是Android BLE开发和BLE开发的新手,我注意到大多数时候,Android在调用onConnectionStateChange之前需要3-7秒才能在我的connectGatt调用之后被触发。这是正常的吗?我很好奇,因为我之前使用过蓝牙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
答案 0 :(得分:0)
对于那些可能对我有用的解决方案感兴趣的人。我找不到任何建议任何特定广告时间间隔的Android文档,但IOs文档建议使用152.5毫秒的间隔。将我的间隔设置为此后,我的应用程序开始发现并更快地连接到蓝牙。感谢Emil,我指出了正确的方向。
这是我上面提到的IOs文档页面。 https://developer.apple.com/library/content/qa/qa1931/_index.html