You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

BLE写入后onCharacteristicChanged未触发,需实现十进制转十六进制功能

Hey Kumar, let's work through your two BLE and conversion issues step by step. I'll break down solutions for each problem with code adjustments tailored to your existing implementation.


1. Fixing BLE Response Data Retrieval

Looking at your current BluetoothGattCallback code, there are a few key gaps preventing you from receiving responses after writing to the BLE device. Here's what to adjust:

a. Correctly Set Up Notifications for the Receive Characteristic

Your onCharacteristicWrite method is enabling notifications on the write characteristic instead of the receive characteristic (the one with AppConstant.RECEIVE_UUID). Additionally, BLE notifications require configuring the Client Characteristic Configuration Descriptor (CCCD) to tell the device to send updates.

Update your onServicesDiscovered method to configure notifications for the receive characteristic:

@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
    super.onServicesDiscovered(gatt, status);
    clientGatt = gatt;
    if (status == BluetoothGatt.GATT_SUCCESS) {
        BluetoothGattService service = gatt.getServices().get(2);
        List<BluetoothGattCharacteristic> gattCharacteristics = service.getCharacteristics();
        for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
            if (gattCharacteristic.getUuid().toString().equalsIgnoreCase(AppConstant.RECEIVE_UUID)) {
                readCharacteristic = gattCharacteristic;
                // Enable notifications for the receive characteristic
                gatt.setCharacteristicNotification(readCharacteristic, true);
                // Configure CCCD descriptor to allow notifications
                BluetoothGattDescriptor descriptor = readCharacteristic.getDescriptor(
                        UUID.fromString("00002902-0000-1000-8000-00805f9b34fb")
                );
                descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                gatt.writeDescriptor(descriptor);
            }
            if (gattCharacteristic.getUuid().toString().equalsIgnoreCase(AppConstant.SEND_UUID_STR)) {
                writeCharacteristic = gattCharacteristic;
            }
        }
    }
}

b. Handle Responses in the Right Callback

  • If your BLE device sends responses via notifications, implement the onCharacteristicChanged method to process incoming data:
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
    super.onCharacteristicChanged(gatt, characteristic);
    // Process the response data here
    byte[] responseData = characteristic.getValue();
    if (responseData != null) {
        LogUtils.errorLog("BLE Response", "Received data: " + Arrays.toString(responseData));
        // Convert bytes to your desired format as needed
    }
}
  • If your device requires an explicit read after writing, call readCharacteristic in onCharacteristicWrite (only when the write succeeds):
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
    super.onCharacteristicWrite(gatt, characteristic, status);
    if (status == BluetoothGatt.GATT_SUCCESS && readCharacteristic != null) {
        // Trigger a read on the receive characteristic to get the response
        gatt.readCharacteristic(readCharacteristic);
    }
}

c. Verify Characteristic Permissions

Double-check that your RECEIVE_UUID characteristic has the PROPERTY_NOTIFY or PROPERTY_READ permission (depending on how the device sends responses). You can confirm this by calling readCharacteristic.getProperties() and checking against the BluetoothGattCharacteristic constants.


2. Decimal to Hex Integer Conversion

Converting a decimal value (like 60 minutes) to a hex integer is straightforward in Java—since integers are stored as binary internally, the "hex" representation is just a different way to display the same value. Here are the utility methods you need:

Basic Conversion (Decimal to Hex Value)

If you need the integer value in hex format (e.g., 60 → 0x3c), you don't need to convert the integer itself—you just need to display it as hex. Use these methods:

// Convert decimal to hex string with 0x prefix (e.g., 60 → "0x3C")
private String decimalToHexString(int decimal) {
    return String.format("0x%02X", decimal); // %02X ensures 2-digit uppercase hex
}

// Get the integer value (it's already the same as the hex equivalent—60 is 0x3c in hex)
private int decimalToHexInt(int decimal) {
    return decimal;
}

For BLE Write Operations

If you need to send the decimal value as a byte to the BLE device (e.g., 60 → 0x3c as a byte), cast the integer to a byte:

// Convert decimal to a single byte (works for values 0-255)
private byte decimalToByte(int decimal) {
    return (byte) decimal;
}

// Usage example when writing to BLE:
int minutes = 60;
writeCharacteristic.setValue(new byte[]{decimalToByte(minutes)});
clientGatt.writeCharacteristic(writeCharacteristic);

内容的提问来源于stack exchange,提问作者Kumar Raj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 09:00:36