2013-11-27 218 views
2

我正在使用BLE的Android应用程序中工作。我想写入我连接到的设备服务的特征。使用蓝牙低功耗写入

我的功能是这样的:

public void writeCharacteristic(BluetoothGattCharacteristic characteristic, 
              boolean enabled, String text) { 
    if (mBluetoothAdapter == null || mBluetoothGatt == null) { 
     Log.w(TAG, "BluetoothAdapter not initialized"); 
     return; 
    } 


    characteristic.setValue("7"); 

    boolean status = mBluetoothGatt.writeCharacteristic(characteristic); 


} 

我不为什么值未特性里面写。 我按照此链接中的步骤操作: write with BLE

有人知道我的代码为什么不起作用吗?

非常感谢。 Regards

P.D.为我的英语道歉。

+0

究竟发生了什么? – njzk2

回答

1

在电脑上花了整整一天的时间尝试不同的功能和表单后,我找到了解决方案,这要感谢来自工作的朋友。 我们必须将文本转换为字节,然后将该字节放入字节数组并发送。固定。

byte pepe = (byte) Integer.parseInt(text); 
byte[] charLetra = new byte[1]; 

charLetra[0] = pepe; 

LumChar.setValue(charLetra); 
boolean status = mBluetoothGatt.writeCharacteristic(LumChar); 

无论如何非常感谢您的帮助。

问候。

2

也许你的characteristic接受byte[]价值。尝试通过将String参数转换为byte[]来设置characteristic值与字节数组。你的方法应该是这样的:

public void writeCharacteristic(BluetoothGattCharacteristic characteristic, 
                  String text) { 
    if (mBluetoothAdapter == null || mBluetoothGatt == null) { 
     Log.w(TAG, "BluetoothAdapter not initialized"); 
     return; 
    } 
    byte[] data = hexStringToByteArray(text); 

    characteristic.setValue(data); 

    boolean status = mBluetoothGatt.writeCharacteristic(characteristic); 
} 

private byte[] hexStringToByteArray(String s) { 
    int len = s.length(); 
    byte[] data = new byte[len/2]; 
    for (int i = 0; i < len; i += 2) { 
     data[i/2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character 
       .digit(s.charAt(i + 1), 16)); 
    } 
    return data; 
} 

还要注意的是,status变量返回true,如果写操作启动成功。因此,要获得写入操作结果状态,请使用onCharacteristicWritecallbackBluetoothGattCallback并检查其中的状态。

+0

非常感谢您的快速回答。我想通过蓝牙发送到其他设备的值是从0到127的数字。我使用以下代码:byte [] bytes = ByteBuffer.allocate(4).putInt(Integer.valueOf(text))。array( ); LumChar.setValue(字节);布尔状态= BluetoothGatt.writeCharacteristic(LumChar);而这不起作用,因为它不写任何东西。 – Enzo