2013-11-27 222 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