Androi BLE writeCharacteristics方法总是在Android 5.0及更高版本中返回false

时间:2016-07-29 16:26:05

标签: java android callback bluetooth-lowenergy gatt

我试图用Android设备和定制板之间用BLE模块交换数据。我在Android设备5.0及更高版本上使用characteristicsWrite()方法遇到了一些麻烦。在lover版本中,characteristicsWrite()方法返回true,然后在BleGattCallback中调用onCharacteristicsWrite()回调

写方法:

private void sendMessageToDevice(String message) {

    byte nullByte = 0x00;
    byte[] temp = message.getBytes();
    byte[] tx = new byte[temp.length + 1];
    tx[tx.length - 1] = nullByte;

    System.arraycopy(temp, 0, tx, 0, temp.length);

    characteristicWrite.setValue(tx);

    boolean writeResult = mBluetoothGatt.writeCharacteristic(characteristicWrite);

    Log.d(LOG_TAG, "writeResult"); //true
}

onCharacteristicsWrite方法:

@Override
    public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
        super.onCharacteristicWrite(gatt, characteristic, status);

        Log.d(LOG_TAG, status); // status = 0 - GATT_SUCCESS
    }

但是当我在android设备上执行这段代码时,v。writeCharacteristic()方法的结果总是为false,并且onCharacteristicWrite()回调没有被调用。

有谁能解释我如何在BLE设备和Android 5.0+之间正确建立连接?也许我需要一些针对此类设备的特定方法。 在三星和联想智能手机v5.0 +上测试应用程序。

1 个答案:

答案 0 :(得分:-1)

问题解决了。在获得writeCharacteristic函数的“false”结果后,您只需再次调用discoverServices():

private void sendMessageToDevice(String message) {

        .............

        boolean writeResult = mBluetoothGatt.writeCharacteristic(characteristicWrite);

        if(!writeResult)
           mBluetoothGatt.discoverServices();
}

之后你需要再次调用writeCharacteristic()函数,对我来说结果是“true”。