4

我正在开发一个可以将数据传输到 4.0 蓝牙串行设备的 Android 应用程序。我由 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 蓝牙设备进行数据传输。

4

1 回答 1

2

Android BLE 的工作方式与蓝牙堆栈完全不同,请参阅 Wikipedia 中的 BLE。

要使用 BLE 发送数据,您需要将数据放入特征中并使用 gatt 发送!

1st,你需要检查你的BLE设备,哪个特性用于发送数据,以及使用那个特性来发送数据!

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

请注意,Android BLE 堆栈有问题,一次只能写一次Characteristics,如下面的链接所述!!

你可以查看这篇关于 Android BLE 的帖子,它会让你清楚地了解 Android BLE 回调是如何工作的!

Android BLE,读写特性

于 2014-06-13T01:29:28.260 回答