从Android的蓝牙设备读取数据 [英] Reading data from bluetooth device in android
问题描述
我使用,以蓝牙聊天的蓝牙设备连接,并免费获赠数据。
I am using bluetooth chat in order to connect and recieve data from a bluetooth device.
我用下面的code读取数据:
I use the following code for reading data:
public void run() {
byte[] buffer = new byte[1024];
int bytes;
Log.v("MR", "start listening....");
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
Log.d("MR", "buffer in try");
bytes = mmInStream.read(buffer);
Log.d("MR", "input stream :"+(new String(buffer)));
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(Conn.MESSAGE_READ, bytes, -1, buffer).sendToTarget();
Log.d("MR", "buffer after");
} catch (Exception e) {
Log.e("MR", "Error :"+e.getMessage());
//
connectionLost();
// break;
}
Log.d("MR", "buffer after while");
}
}
该设备所有的时间发送数据,而不会停止。
The device is sending data all the time without stopping.
通过上面的code,我得到的消息:
With the above code I get the message of:
Log.d("MR", "buffer in try");
然后进入下一行:
then it goes to the next line:
bytes=mmInStream.read(buffer);
和永远不会返回从这一呼吁。我想这是因为它开始从设备读取数据,并不会停止,直到它断开。我怎样才能读取一定数量的字节的时间?
and never returns from that call. I guess this is because it starts reading data from the device and doesn't stop until it disconnects. How can I read a certain amount of bytes at a time?
修改
除非它留到字节= mmInStream.read(缓冲);
code,由于它不;吨坐回从设备中的数据?
Unless it stay to the bytes = mmInStream.read(buffer);
code due to that it don;t get any data back on from the device?
推荐答案
我用DataInputStreams而不是因为你可以做的readFully()方法,等待返回前读取一定数量的字节。我的设置是这样的BT连接:
I use DataInputStreams instead as you can do a readFully() method which waits to read a certain number of bytes before returning. I setup the BT connection like this:
BluetoothDevice btDevice = bta.getRemoteDevice(macAddress);
BluetoothSocket btSocket = InsecureBluetooth.createRfcommSocketToServiceRecord(
btDevice, UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"), false);
btSocket.connect();
InputStream input = btSocket.getInputStream();
DataInputStream dinput = new DataInputStream(input);
后来,当我想读书,我使用的readFully的:
then later on when I want to read I use readFully:
dinput.readFully(byteArray, 0, byteArray.length);
这篇关于从Android的蓝牙设备读取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!