2014-06-13 82 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