通过地址直接连接的Android BLE失败

问题描述 投票:0回答:2

所以我有这种情况。如果我扫描新的LE设备并连接到找到的任何设备,我就能成功连接,但如果我将该设备地址存储在内存中,请关闭应用程序并再次打开,然后尝试直接连接到我的onConnectionStateChange我得到newState为BluetoothProfile.STATE_DISCONNECTED大部分时间,但并非总是如此。

这似乎发生在Galaxy s7上,但不是在我的其他廉价平板电脑上。

我的连接逻辑如下所示:

    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

任何有关如何处理这一点的建议将不胜感激

android bluetooth bluetooth-lowenergy android-bluetooth
2个回答
1
投票

你可以(也应该)在这里使用你的BluetoothGattCallback。发现服务会触发BluetoothGattCallback.onServicesDiscovered()。您应该在日程安排中使用该回调。

我发现最好实现一个延迟的重试循环。这样,当连接完全初始化时,您将获得更好的体验。立即尝试,如果回调未在2-300ms内触发,请再试一次,然后再等等,直到您觉得自己已经尝试了足够长的时间。


0
投票

好吧,我的问题是DELAY_BEFORE_DISCOVERING,大约600毫秒。看来三星Galaxy s7至少需要1500毫秒。有了它,我每次尝试都能连接。

© www.soinside.com 2019 - 2024. All rights reserved.