android - Android BLE - 连接外围设备后的问题
问题描述
目前,我能够扫描蓝牙设备,找到合适的外围设备,连接到它,然后写入特征/读取它的响应。连接外围设备后,问题开始出现。更糟糕的是,这种行为在何时发生时不一致。随着时间的推移,它最终会遇到这个问题,但有时是在第一次连接到外围设备之后,有时是在多次交互之后。每当我停止并重新启动应用程序,点击扫描,我就可以再次找到设备,连接等。
我的一个想法是,当重新扫描发生时,应用程序可能没有完全断开连接。这对于为什么应用程序找不到外围设备是有道理的。但是,我不确定从外围设备断开连接时还能做什么。我认为扫描问题是正在发生的不同问题的症状。
这是我的断开逻辑:
public void stopService() {
if (bluetoothGatt != null) {
Log.d(BLE.TAG, "Closing bluetooth gatt connection...");
bluetoothGatt.close();
}
bluetoothGatt = null;
Log.d(BLE.TAG, "Updating service status...");
updateState(BluetoothStatus.NONE);
}
更新状态是一种在状态改变时引发事件的方法。
我正在覆盖 onConnectionStateChange 方法:
@RequiresPermission(Manifest.permission.BLUETOOTH)
@Override
public void onConnectionStateChange(final BluetoothGatt gatt, int status, final int newState) {
super.onConnectionStateChange(gatt, status, newState);
Log.v(BLE.TAG, "onConnectionStateChange: status: " + status + " newState: " + newState);
if (status != BluetoothGatt.GATT_SUCCESS || newState == BluetoothProfile.STATE_DISCONNECTED) {
gatt.close();
stopService();
updateState(BluetoothStatus.NONE);
} else {
if (newState == BluetoothProfile.STATE_CONNECTED) {
gatt.discoverServices();
} else if (newState == BluetoothProfile.STATE_CONNECTING) {
updateState(BluetoothStatus.CONNECTING);
}
}
}
扫描逻辑:
final BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
@RequiresPermission(Manifest.permission.BLUETOOTH)
@Override
public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord) {
List<UUID> uuids = parseUUIDs(scanRecord);
if(uuids.contains(mConfig.uuid)) {
if(!foundDeviceAddressList.contains(device.getAddress())) {
Log.v(TAG, "onLeScan " + device.getName() + " mac address: " + device.getAddress() + " uuids: " + uuids);
foundDeviceAddressList.add(device.getAddress());
if (onScanCallback != null && (mConfig.uuid == null || uuids.contains(mConfig.uuid))) {
threadManager.runOnMainThread(new Runnable() {
@Override
public void run() {
onScanCallback.onDeviceDiscovered(device, rssi);
}
});
}
}
}
}
};
更新: 所以即使在调用 stopService() 之后,我也能够验证连接状态是否保持连接。有没有办法确认连接状态被回收了?
解决方案
推荐阅读
- python - 在 pymongo 代码中出现错误 InvalidBson。如何解决这个问题?
- swift - UICollectionViewDiffableDataSource 实时更新
- swift - 我想做一个 if 语句,当用户点击时,每个图像都是全屏的
- javascript - 如何从 react.js 中的 redux 存储向引导表插入数据?
- python - 使用 Matplotlib.image 堆叠图像
- docker - 找不到当前平台“debian-openssl-1.0.x”的查询引擎二进制文件
- python-3.x - 使用 € 作为散景中 NumeralTickFormatter 中的货币符号
- c++ - 禁用复制构造函数和赋值运算符时将引用实例传递给静态方法
- xcode - iOS 14 Datepicker 问题,preferredDatePickerStyle 设置为紧凑
- codenameone - 调试和 AppStore iOS 构建有什么区别