用于从蓝牙流式传输的 Android 缓冲读取器 [英] Buffered Reader for Android Streaming from Bluetooth
问题描述
嘿伙计们,我正在尝试从蓝牙设备读取流,连续流式传输整数,如下所示:
Hey guys so I'm trying to read a stream from a bluetooth device continuously streaming integers like this:
-11
121
123
1234
-11
我可以使用我在网上找到的一些代码,但要进行一些处理,数字需要是整数而不是字符串,parseInt 占用了太多 CPU,我尝试使用缓冲流但无济于事.
I have everything working with some code I found online, but to do some of the processing the numbers need to be ints as opposed to Strings, parseInt is taking up too much CPU, and I tried using a buffered stream with no avail.
这是当前的方法:
void beginListenForData()
{
final Handler handler = new Handler();
final byte delimiter = 10; //This is the ASCII code for a newline character
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable()
{
public void run()
{
while(!Thread.currentThread().isInterrupted() && !stopWorker)
{
try
{
int bytesAvailable = mmInputStream.available();
if(bytesAvailable > 0)
{
byte[] packetBytes = new byte[bytesAvailable];
mmInputStream.read(packetBytes);
for(int i=0;i<bytesAvailable;i++)
{
byte b = packetBytes[i];
if(b == delimiter)
{
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
final String data = new String(encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable()
{
public void run()
{
myLabel.setText(data);
}
});
}
else
{
readBuffer[readBufferPosition++] = b;
}
}
}
}
catch (IOException ex)
{
stopWorker = true;
}
}
}
});
workerThread.start();
}
如果有区别,数据来自 Arudino,我可以修改它的流式传输方式.
If it makes a difference, the data is coming from an Arudino, which I can modify the way it streams.
谢谢!
推荐答案
使用 DataInputStream
包裹在 BufferedInputStream
和 readInt()
> 方法.这当然假设网络字节顺序为整数.
Use a DataInputStream
wrapped around a BufferedInputStream
, and the readInt()
method. This assumes network byte order in the integers of course.
忘记所有这些 arraycopy()
的东西.
Forget all this arraycopy()
stuff.
这篇关于用于从蓝牙流式传输的 Android 缓冲读取器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!