记录Android 部分手机向低功耗蓝牙写入特征值失败问题。

1,304 阅读1分钟

部分Android手机向低功耗蓝牙写入特征值失败,测试出低端机出现频率很高

BluetoothGatt.writeCharacteristic 写入时mDeviceBusy变量值为true导致写入特征失败

image.png

解决方法:

1,延迟设置特征值(低效不可靠)

new Timer().schedule(new TimerTask() {
    @Override
    public void run() {
        result = bluetoothGatt.writeCharacteristic(characteristic);
  }
},2000)

2,通过反射取到变量mDeviceBusy的值,为false后再去写入特征值

private static long CHARACTER_TIMEOUT = 2000;

private boolean isDeviceBusy(BluetoothGatt mBluetoothGatt){
    boolean state = false;
    try {
        state = (boolean)readField(mBluetoothGatt,"mDeviceBusy");
        Log.e(TAG,"isDeviceBusy:"+state);
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    }
    return state;
}

public Object readField(Object object, String name) throws IllegalAccessException, NoSuchFieldException {
    Field field = object.getClass().getDeclaredField(name);
    field.setAccessible(true);
    return field.get(object);
}

public boolean writeCharacteristicByUuid1(String address, byte[] value, UUID serviceUUID, UUID characteristicUUID) {
    BluetoothGatt bluetoothGatt = getBluetoothGatt(address);
    long enterTime = System.currentTimeMillis();
    while ((System.currentTimeMillis() - enterTime) < CHARACTER_TIMEOUT) {
        if(isDeviceBusy(bluetoothGatt)){
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }else {
            break;
        }
    }
    try {
        BluetoothGattCharacteristic characteristic = gattCharacteristic(bluetoothGatt, serviceUUID, characteristicUUID);
        if (characteristic != null) {
            characteristic.setValue(value);
            boolean result = bluetoothGatt.writeCharacteristic(characteristic);
            Log.e(TAG, "result:" + result);
            return result;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}