我正在按照Android BLE API的指导,尝试连接并读取设备数据。扫描、连接和读取数据都没有问题,但是问题在于连接恰好在30秒后断开,只能在短暂的时间(<10秒)内重新连接。这是我连接设备GATT服务器的代码:
protected BluetoothGatt initGattServer(BluetoothDevice device, final ConnectionCallback callback, final DataCallback dataCallback) {
Log.d("INIT GATT SERVER", device.getName());
this.gatt = device.connectGatt(context, true, new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState){
Log.d("GATT CONNECTION", "CHANGED -- status: " + status + " newState: " + newState);
if(callback != null){
callback.onConnectionStateChanged(newState);
}
gattConnectionState = newState;
if(status == BluetoothGatt.GATT_SUCCESS){
if(newState == BluetoothProfile.STATE_CONNECTED){
gatt.discoverServices();
}
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status){
gattServices.clear();
gattServices.addAll(gatt.getServices());
callback.onServicesDiscovered(gatt);
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status){
handleCharacteristicChanged(characteristic, status, dataCallback);
}
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status){
handleCharacteristicChanged(characteristic, status, dataCallback);
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic){
handleCharacteristicChanged(characteristic, BluetoothGatt.GATT_SUCCESS, dataCallback);
}
});
refreshDeviceCache(gatt);
return this.gatt;
}
问题在于,我收到了意外的回调到onConnectionStateChange,其状态为BluetoothProfile.STATE_DISCONNECTED,接着是BluetoothProfile.STATE_CONNECTED。这种断开连接和重新连接的过程在服务运行期间重复发生,因此连接不够稳定。我正试图连接的设备供应商有一个应用程序来维护它的连接,但我的连接却没有。可能的原因是什么?