首页 > 解决方案 > 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() 之后,我也能够验证连接状态是否保持连接。有没有办法确认连接状态被回收了?

标签: androidbluetooth-lowenergy

解决方案


推荐阅读