Android使用inputStream从蓝牙读取
我编写了一个程序,通过 SPP 不断从蓝牙读取数据,并将流中的内容打印到编辑文本框中。我有以下线程:
myTimer = new Timer();
myTimer.schedule(new TimerTask(){
@Override
public void run(){
TimerMethod();
}
},0,1000);
private void TimerMethod(){this.runOnUiThread(startReading);}
private Runnable startReading = new Runnable(){
public void run(){
EditText _txtArea = (EditText) findViewById(R.id._txtArea);
try{
inStream = btSocket.getInputStream();
}catch (IOException e3) {
_txtArea.append("inStream establishment Failed!");
}
现在传入的消息可以是任意大小,我想继续阅读,直到没有任何内容可供阅读。我尝试了一个实现,我做了这样的事情:
byte[] msgIn = new byte[15];
inStream.read(msgIn, 0, 15);
int len = msgIn.length;
for (int i=0; i<len; i++){
out = new Character ((char) msgIn[i]).toString();
_txtArea.append(out);
但这将读取限制为 15 个字节,并且代码似乎不是很有效。如果有人想知道为什么我有以下行 out = new Character ((char) msgIn[i]).toString();这是因为传入的数据是 ASCII 格式,我将其转换为字符。读取完所有内容后,当没有其他内容可读取时,也使用此方法,程序会挂起。有谁知道我可以继续阅读直到所有数据都被读取的方法吗?
I have written a program that constantly reads from the Bluetooth via SPP and prints the contents in the stream to a edittext box. I have the following thread:
myTimer = new Timer();
myTimer.schedule(new TimerTask(){
@Override
public void run(){
TimerMethod();
}
},0,1000);
private void TimerMethod(){this.runOnUiThread(startReading);}
private Runnable startReading = new Runnable(){
public void run(){
EditText _txtArea = (EditText) findViewById(R.id._txtArea);
try{
inStream = btSocket.getInputStream();
}catch (IOException e3) {
_txtArea.append("inStream establishment Failed!");
}
Now the msg's incoming can be of any size and I want to keep reading until there isn't anything remaining to be read. I tried an implementation where i did something like this:
byte[] msgIn = new byte[15];
inStream.read(msgIn, 0, 15);
int len = msgIn.length;
for (int i=0; i<len; i++){
out = new Character ((char) msgIn[i]).toString();
_txtArea.append(out);
But that limits the read to 15 bytes and the code doesn't seem very effecient. If anyone is wondering why i have the following line out = new Character ((char) msgIn[i]).toString(); it's because the data coming in is in ASCII i am converting it to a char. Also using this method after reading all of the contents when there is nothing else to read the program hangs. Does anyone know a way i can keep reading until all of the data has been read?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想通了,对于那些感兴趣的人来说,这是因为应该在读取之前关闭流,以便在发送所有数据后 inputStream.read() 将能够达到 -1
I figured it out, for those who are interested it is because the stream should be closed before a read so that inputStream.read() will be able to reach -1 after all data has been sent