Android 从 InStream 读取永远无法解决(没有数据读取,没有崩溃)
读取它
我这里有一个设备,我可以向其发送状态请求命令,然后使用bytes = mmInStream.read(statusBuffer);
。不过,当它改变状态时我遇到了麻烦。有时我会返回当前状态,有时程序会挂在该线上并且不执行任何其他操作。它不会崩溃,不会移动到下一行或其他任何东西。我只能通过关闭设备并切断连接来继续。
我们这里有一个黑莓手电筒,根本没有这个错误,所以它一定是我的代码。
谁能给我一些故障排除提示?下面是读取设备当前状态的 while 循环。
while (true) {
getStatus();
try {
bytes = 0;
while(bytes < 1){
bytes = mmInStream.read(statusBuffer);
if (bytes != 0){
response = new String(statusBuffer);
//Handle response code
}
}
}
} catch (Exception e) {
Log.e(TAG, "disconnected FROM WHILE TRUE LOOP", e);
connectionLost();
break;
}
}
I have a device here that I can send a status request command to, and then I read it using
bytes = mmInStream.read(statusBuffer);
I'm having trouble when it changes it's status though. Sometimes I will get back the current status, other times the program will hang on that line and not do anything else. It doesn't crash, move onto the next line or anything. I can only move on by turning off the device and severing the connection.
We have a blackberry torch here that does not have this error at all so it must be my code.
Can anyone give me some troubleshooting tips? Below is the while loop that reads the devices current status.
while (true) {
getStatus();
try {
bytes = 0;
while(bytes < 1){
bytes = mmInStream.read(statusBuffer);
if (bytes != 0){
response = new String(statusBuffer);
//Handle response code
}
}
}
} catch (Exception e) {
Log.e(TAG, "disconnected FROM WHILE TRUE LOOP", e);
connectionLost();
break;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果没有可用字节,则读取将返回 -1,您会错过比较并继续循环。
如果您的行以 \n 字符结尾,那么通过 BufferedReader 等读取它会更容易。不管怎样,你的循环设计得不是很好。
做
{
//读取字节
//将结果存储在byteRead中
}//do
while( byteRead != -1 )
问候,
史蒂芬
If there is no byte available, -1 is returned by read, you miss your comparison and you go on looping.
If your line ends with a \n char it would be far easier to read it through an BufferedReader for instance. Anyhow, your loop is not very well designed.
do
{
//read bytes
//store the result in byteRead
}//do
while( byteRead != -1 )
Regards,
Stéphane