简体   繁体   English

从蓝牙插座读取

[英]Reading from Bluetooth socket

I have a problem with reading from Bluetooth socket.我在从蓝牙套接字读取时遇到问题。 I create the socket:我创建了套接字:

private OutputStream outputStream;
private InputStream inStream;
socket=device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
socket.connect();
outputStream = socket.getOutputStream();
inStream = socket.getInputStream();

After connection is established I send some instructions to the Bluetooth device after which I need to get an answer back(answer is always the same 5 bytes).建立连接后,我向蓝牙设备发送一些指令,之后我需要得到回复(答案总是相同的 5 个字节)。 But from time to time when I do this:但有时当我这样做时:

byte[] packetBytes = new byte[5];
inStream.read(packetBytes);

the app freezes.应用程序冻结。 I tried inputstream.available and used it with previous devices, but it would always return 0 here.我尝试了 inputstream.available 并将其与以前的设备一起使用,但它总是会在这里返回 0。 And I tried waiting before reading but still nothing.我试着在阅读之前等待,但仍然没有。 When I try those same commands on PC I get an answer.当我在 PC 上尝试相同的命令时,我得到了答案。

For anybody that is having the same problem as me.对于任何和我有同样问题的人。 For now the solution that I am using is a new Thread that constantly reads from an input socket with inStream.read(packetBytes);现在我使用的解决方案是一个新的线程,它不断地从输入套接字中读取 inStream.read(packetBytes);

When something is read we just send it to our main Thread to be processed.当读取某些内容时,我们只需将其发送到我们的主线程进行处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM