AndroidBLE开发过程中遇到的问题记录

Android BLE 开发过程中遇到的问题记录

1.断开连接后出现133错误

在断开连接之后再次连接经常会出现133错误,并且难以连接成功,处理方式如下:

首先在重连的时候先将Gatt缓存进行清理:

    public boolean refreshDeviceCache() {
        if (mBluetoothGatt != null) {
            try {
                BluetoothGatt localBlueToothGatt = mBluetoothGatt;
                Method localMethod = localBlueToothGatt.getClass().getMethod("refresh", new Class[0]);
                if (localMethod != null) {
                    Boolean bool = ((Boolean) localMethod.invoke(localBlueToothGatt, new Object[0])).booleanValue();
                    return bool;
                }
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e2) {
                e2.printStackTrace();
            } catch (IllegalAccessException e3) {
                e3.printStackTrace();
            }
        }
        return false;
    }

然后将Gatt连接进行close操作:

    mBluetoothGatt.close();
    mBluetoothGatt = null;

再次连接时,使用一个全新的Gatt对象进行连接操作,而且在连接之前再次确认Gatt连接是否已经释放:

    /**
     * 连接设备Gatt
     *
     * @param device 设备
     */
    private void connectDevice(final BluetoothDevice device) {
       if (mBluetoothAdapter == null) {
           Log.d(TAG, "connectDevice: BluetoothAdapter not initialized.");
           return;
       }
       if (!mBluetoothAdapter.isEnabled()) {
           Log.d(TAG, "connectDevice: BluetoothAdapter is disabled");
           return;
       }
       if (device == null) {
           Log.d(TAG, "connectDevice: Unspecified device.");
           return;
       }
       //防止连接出现133错误, 不能发现Services
       if (mBluetoothGatt != null || getState() == State.Connecting) {
           Log.d(TAG, "connectDevice: closeGatt");
           mBluetoothGatt.disconnect();
           close();
       }
       if (mBluetoothGatt != null && mBluetoothGatt.getDevice() != null && mBluetoothGatt.getDevice().equals(device)) {
           Log.d(TAG, "connectDevice: Trying to use an existing mBluetoothGatt for connection.");
           mBluetoothGatt.connect();
       } else {
           Log.d(TAG, "connectDevice: Trying to create a new connection.");
           if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
               mBluetoothGatt = device.connectGatt(MyApplication.getInstance(), false, mGattCallback, BluetoothDevice.TRANSPORT_LE);
           } else {
               mBluetoothGatt = device.connectGatt(MyApplication.getInstance(), false, mGattCallback);
           }
       }
    }

这种操作下来即使出现133,也能在多次尝试重连之后连接成功。

其次,出现133也很有可能与硬件有关,笔者使用的硬件硬件在初期经常出现133错误,但硬件进行了调优之后出现的频率大大降低了,所以并不是所有的问题都是Android设备的错。

2.交互时出现128错误

开发过程中命令交互的时候出现128错误,连接中止:

这个错误出现的原因是因为gatt命令交互并不能并行操作,一旦上一个命令还未反馈结束就再次发送下一个命令就会出现128错误。

3.发现服务之后立即进行连接,部分机型无法成功

在开发过程中发现,建立连接过程中,发现服务之后如果立即书写特征值,可能出现部分机型无法成功连接的情况:

通过长期测试,目前将每一条特征值的书写进行了700ms的延迟,暂时可以支持绝大部分机型。

    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        super.onServicesDiscovered(gatt, status);
        mBluetoothGatt = gatt;
        if (status == BluetoothGatt.GATT_SUCCESS) {

            Log.d(TAG, "onServicesDiscovered. status = " + status);
            //UUID serviceUuid = UUID.fromString("00001800-0000-1000-8000-00805f9b34fb");
            BluetoothGattService service = gatt.getService(mServiceUuid);
            if (BuildConfig.DEBUG) Log.d(TAG, "service.getUuid():" + service.getUuid());

            if (service != null) {

                List characteristics = service.getCharacteristics();
                for (int j = 0; j < characteristics.size(); j++) {
                    final BluetoothGattCharacteristic characteristic = (BluetoothGattCharacteristic) characteristics.get(j);
                    Log.d(TAG, "characteristic = " + characteristic.getUuid().toString());
                    Log.d(TAG, String.format("characteristic.properties = %X", characteristic.getProperties()));
                    if ((characteristic.getProperties() & (BluetoothGattCharacteristic.PROPERTY_NOTIFY | BluetoothGattCharacteristi
                        gatt.setCharacteristicNotification(characteristic, true);

                        sHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString(CLIENT_CHARAC
                                    if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
                                        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                                        mBluetoothGatt.writeDescriptor(descriptor);
                                    } else if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_INDICATE) > 0
                                        descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
                                        mBluetoothGatt.writeDescriptor(descriptor);
                                    }
                                } catch (Exception e) {
                                    reScanDevice();
                                    e.printStackTrace();
                                }
                            }
                        }, 700 * j);
                    }
                }
            }
        } else {
            reScanDevice();
            Log.d(TAG, "onServicesDiscovered. status = " + status);
        }
    }

4.BLE蓝牙命令交互确保是有序串行的

由于BLE蓝牙命令交互时串行的所以在开发过程中对此必须严格遵守,异常出现的并行命令极有可能造成各种问题,而且不容易定位bug,当然这部分可以使用第三方封装好的库来做。

5.各品牌手机省电策略引起的问题

华为: 非常严格,如果不开启任何白名单,息屏后五分钟之内应用都杀了,简单开启后台任务白名单,息屏不会被杀,但是蓝牙连接经常被断开,后台无法开启扫描,点亮屏幕才会正常工作,解决办法,开启所有的白名单吧。

小米: 开启白名单之后就可以正常使用了,但是如果一开始在未开启白名单的状态下使用蓝牙,多次扫描后,会报告蓝牙扫描错误,只有开启白名单,重启蓝牙才可以。

OV: 这俩手机打开基本的白名单之后还需要额外确认是否开启的定位权限,闭着用来测试的OV系统版本中定位权限开关很深,所以特别提一下。

魅族:基本的白名单即可;

三星:开启只能管理器中白名单之后就可以随意折腾了。

Nexus/Piexl:低版本随意折腾,7.0以后有一些简单的电量管理白名单可以开启。

请善待那些信任你放开手让你折腾的ROM! Orz.

5.关于与硬件设备之间的连接参数设置

在与硬件进行调试的过程中发现,Android相比于iOS的BLE连接在每次连接后都会默认去更新连接参数,不知道是否与各家定制的ROM有关。

6.扫描模式参数与连接模式参数设置

在蓝牙扫描方法中提供了一个扫描模式参数:

    final ScanSettings scanSettings = new ScanSettings.Builder()
            .setScanMode(mScanMode)
            .build();

这里的扫描模式有三种:

ScanSettings.SCAN_MODE_LOW_POWER:节省功耗优先。
ScanSettings.SCAN_MODE_BALANCED:功耗与效率平衡。
ScanSettings.SCAN_MODE_LOW_LATENCY:效率优先优先。

可根据需求进行选择

在BLE连接的方法中,提供了一个连接模式参数:

    mBluetoothGatt = device.connectGatt(context, false, mGattCallback, BluetoothDevice.TRANSPORT_LE);

这里的模式选择有三种:

BluetoothDevice.TRANSPORT_AUTO:对于GATT连接到远程双模设备无物理传输优先。
BluetoothDevice.TRANSPORT_BREDR:GATT连接到远程双模设备优先BR/EDR。
BluetoothDevice.TRANSPORT_LE:GATT连接到远程双模设备优先BLE。

这里选择优先BLE。

    原文作者:我爱小白小白爱大开
    原文地址: https://www.jianshu.com/p/69c0877f97e2
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞