问题描述
我正在开发一个Android应用,该应用可以将数据传输到4.0蓝牙串行设备.我以LeGatt android示例项目( http://developer.android.com/samples/BluetoothLeGatt/index.html ).在此项目中,它们连接到设备,但与传输数据无关.
I'm developing an Android app than can transmit data to a 4.0 Bluetooth serial device. I'm guiding by LeGatt android sample project (http://developer.android.com/samples/BluetoothLeGatt/index.html). In this project, they connect to the device, but nothing about transmission data.
对于2.0蓝牙,我可以创建一个Socket,InputStream和OutputStream来传输数据,如下所示:
For 2.0 bluetooth I can create a Socket, InputStream and OutputStream to transmit the data, something like this:
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蓝牙中,我无法创建套接字,因为此方法不起作用
But in 4.0 Bluetooth I can't create the Socket, because this method doesn't works
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蓝牙设备进行数据传输.
Can someone help me to reach the data transmission using my 4.0 bluetooth device.
推荐答案
Android BLE的工作原理与蓝牙协议栈完全不同,请参阅Wikipedia中的BLE.
Android BLE works entirely different from the Bluetooth stack, read about BLE in Wikipedia.
要使用BLE发送数据,您需要将数据放入特征并使用gatt发送!
To send a data using BLE, you need to place your data in characteristics and send it using the gatt!
首先,您需要检查您的BLE设备,该设备用于发送数据的特性,而该特性用于发送数据!
1st, you need to check your BLE device, which characteristic is used for sending data and used that characteristics for sending data!
byte[] data; //Place your data into this array of byte
characteristic.setValue(data);
gatt.writeCharacteristic(characteristic);
请注意,Android BLE堆栈有问题,您一次只能写一次特性,如下面的链接所述!
Please take note that Android BLE stack is buggy, you can only writeCharacteristics once at a time, as mention in the link below!!
您可以查看有关Android BLE的这篇文章,它将使您清楚地了解Android BLE回调的工作方式!
You can check this post about Android BLE, it will give you a clear understanding of the how the Android BLE callbacks work!
这篇关于创建用于4.0蓝牙传输的套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!