我正在开发一个 Android 应用程序,可以将数据传输到 4.0 蓝牙串行设备。我正在指导 LeGatt android 示例项目(http://developer.android.com/samples/BluetoothLeGatt/index.html 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 蓝牙设备实现数据传输吗?
Android BLE 的工作原理与蓝牙堆栈完全不同,请阅读 Wikipedia 中有关 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,读写特性 https://stackoverflow.com/questions/24008249/android-ble-read-and-then-write-characteristics
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)