所以我有这种情况。
如果我扫描新的le设备并连接到找到的任何设备,我就能成功连接,但如果我将该设备地址存储在内存中,关闭应用程序并再次打开,然后尝试在我的onconnectionstatechange中直接连接我将newstate设置为bluetoothprofile.state_大多数时间断开连接,但并不总是如此。
这似乎发生在GalaxyS7上,但在我的另一个廉价平板电脑上没有。
我的连接逻辑如下:
BluetoothDevice bluetoothDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(
device.getAddress());
Log.i(TAG, "Found device: " + bluetoothDevice.getAddress()
+ " (" + bluetoothDevice.getName() + ") Type: " + bluetoothDevice.getType());
bluetoothGatt = bluetoothDevice.connectGatt(context, false, new BluetoothGattCallback() { <..> }, BluetoothDevice.TRANSPORT_LE);
我的onconnectionstatechange方法如下:
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
Log.i(TAG, "New connection state: " + newState);
if (newState == BluetoothProfile.STATE_CONNECTED) {
Log.i(TAG, "Connection successful");
new Handler(Looper.getMainLooper()).postDelayed(
gatt::discoverServices, DELAY_BEFORE_DISCOVERING);
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
if (status == CONNECTION_ERROR) { // Error 133
Log.i(TAG, "Connection error. Trying again.");
connect(device);
} else {
bluetoothGatt.close();
Log.i(TAG, "Disconnected");
}
}
}
日志如下所示:
2019-03-06 08:26:20.415 5905-5905/app I/LeBluetoothDevice: Write status: true
2019-03-06 08:26:20.417 5905-7919/app I/LeBluetoothDevice: Characteristic write status: 0
2019-03-06 08:26:21.069 5905-9996/app V/FA: Inactivity, disconnecting from the service
2019-03-06 08:26:26.151 5905-7919/app D/BluetoothGatt: onClientConnectionState() - status=8 clientIf=9 device=00:0D:19:00:88:D5
2019-03-06 08:26:26.153 5905-7919/app I/LeBluetoothDevice: New connection state: 0
2019-03-06 08:26:26.154 5905-7919/app D/BluetoothGatt: close()
2019-03-06 08:26:26.155 5905-7919/app D/BluetoothGatt: unregisterApp() - mClientIf=9
2019-03-06 08:26:26.163 5905-7919/app I/LeBluetoothDevice: Disconnected
关于如何处理这个问题的任何建议都将不胜感激