创建一个4.0蓝牙传输的套接字

时间:2014-06-13 01:12:39

标签: java android sockets bluetooth transmission

我正在开发一款Android应用,而不是将数据传输到4.0蓝牙串行设备。我是由LeGatt android示例项目(http://developer.android.com/samples/BluetoothLeGatt/index.html)指导的。在这个项目中,他们连接到设备,但没有关于传输数据。

对于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蓝牙中,我无法创建Socket,因为这种方法不起作用

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蓝牙设备进行数据传输。

1 个答案:

答案 0 :(得分: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堆栈有问题,您只能一次编写一个特性,如下面的链接所示!!

您可以查看有关Android BLE的帖子,它会让您清楚地了解Android BLE回调的工作方式!

Android BLE, read and write characteristics