Android BLE设备每30秒连续断开连接并重新连接

时间:2017-06-27 17:02:19

标签: android bluetooth bluetooth-lowenergy

我正在关注Android's BLE apis尝试从设备连接读取数据。扫描,连接和读取都很好,但问题是在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;
}

问题是我收到带有BluetoothProfile.STATE_DISCONNECTED的onConnectionStateChange的意外回调,然后是BluetoothProfile.STATE_CONNECTED。断开连接重新连接阶段会在其运行的服务期间重复进行,因此连接不牢固。我尝试连接的设备的供应商有一个应用程序维护它的连接,但我的不是。可能是什么原因?

1 个答案:

答案 0 :(得分:1)

结果显示Mark Ch在建议可能存在空闲超时时是正确的。在该设备的情况下,它是30秒,因此每29秒或更少的时间执行读取会阻止断开连接。只是希望他们会在文档中提到这一点!