2014-06-13 30 views
1

我正在開發一個Android應用程序,可以將數據傳輸到4.0藍牙串行設備。我由LeGatt android示例項目(http://developer.android.com/samples/BluetoothLeGatt/index.html)指導。在這個項目中,他們連接到設備,但沒有關於傳輸數據。爲4.0藍牙傳輸創建一個插座

2.0藍牙,我可以創建一個Socket,InputStream和OutputStream來傳輸數據,這樣的事情:

protected BluetoothSocket mySocket = null; 
private InputStream MyInStream; 
private OutputStream MyOutStream; 
try { 
         Method m = mBluetoothDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class}); 
         tmp = (BluetoothSocket) m.invoke(mBluetoothDevice, Integer.valueOf(1)); 
        } catch (Exception e) { 
         textViewLog.append("\n"+"CONNECTION IN THREAD DIDNT WORK"); 
        } 
        mySocket = tmp; 

        try { 
         mySocket.connect(); 
        } catch (IOException e) { 
         textViewLog.append("\n"+e.getMessage()); 
         textViewLog.append("\n"+"CONNECTION IN THREAD DIDNT WORK 2"); 
        } 

        try { 
         MyInStream = mySocket.getInputStream(); 
        } catch (Exception e) { 
         e.printStackTrace(); 
        } 

try { 
        MyOutStream = mySocket.getOutputStream(); 
       } catch (IOException e) { 
        textViewLog.append("\nERROR: "+e.getMessage()); 
       }  

       try { 
        MyOutStream.write((letra+"\r").getBytes()); 
       } catch (IOException e) { 
        textViewLog.append("\nERROR: "+e.getMessage()); 
       } 

但在4.0藍牙我無法創建插槽,因爲此方法不作品

try { 
          Method m = mBluetoothDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class}); 
          tmp = (BluetoothSocket) m.invoke(mBluetoothDevice, Integer.valueOf(1)); 
         } catch (Exception e) { 
          textViewLog.append("\n"+"CONNECTION IN THREAD DIDNT WORK"); 
         } 

有人可以幫助我使用我的4.0藍牙設備達到數據傳輸。

+0

您不需要爲BLE使用輸入/輸出流!它工作不同! – Tim

回答

2

Android BLE的作品完全不同於藍牙堆棧,請閱讀維基百科中的BLE。

要使用BLE發送數據,您需要將數據放入特徵中並使用gatt發送它!

1,您需要檢查您的BLE設備,該特性用於發送數據並使用該特性發送數據!

byte[] data; //Place your data into this array of byte 
characteristic.setValue(data); 
gatt.writeCharacteristic(characteristic); 

請大家注意,Android的BLE堆棧是越野車,你只能writeCharacteristics一次的時間,如下面的鏈接提!

您可以查看關於Android BLE的這篇文章,它會讓您清楚瞭解Android BLE回調的工作原理!

Android BLE, read and write characteristics

+0

您好Tim.Thaks爲您有用的答案。 – Orlando

+0

嗨@Tim,你好嗎 我浪費了很多時間試圖通過特性發送數據,但我做不到! (http://stackoverflow.com/questions/24720029/null-pointer-exception-error-sending-a-characteristic-ble-android?noredirect=1#comment38341920_24720029)(http://stackoverflow.com/questions/24686163/如果你有關於此事的良好文檔或完成此項目的項目,我將不勝感激。 – Orlando

+0

只是使用gatt.writeCharacteristic(特性); 發送數據,請確保您使用正確的特性,以及您正在使用哪個BLE模塊?檢查BLE設備製造商(用戶手冊),看看他們是否需要某種協議來發送數據! – Tim