【发布时间】:2021-07-07 16:23:28
【问题描述】:
我正在接收来自 HC-05 的实时数据,只是从 0 到 1023 的数字。 SleepDuration 变量用于从 HC-05 获取数据之间的睡眠持续时间,用户可以在 1 秒到 2 秒之间选择,这就是问题所在:
当用户为 SleepDuration 选择 1 秒时,程序运行良好,但当他选择超过 1 秒时,该线程在获得少量数据后永远休眠。
这是我接收数据的代码:
public void run() {
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
// Read from the InputStream
try {
bytes = mmInStream.read(buffer);
incomingMessage = new String(buffer, 0, bytes);
try {
sleep(SleepDuration);
} catch (InterruptedException e) {
e.printStackTrace();
}
} catch (IOException e) {
Log.e(TAG, "write: Error reading Input Stream. " + e.getMessage());
break;
}
}
}
【问题讨论】:
-
当没有更多数据要读取时它会阻塞吗?
-
@FrancescoRe 不,它会无缘无故地阻止
-
你是在主线程还是在单独的线程中执行代码?
-
一个单独的线程@FrancescoRe
-
显示更多关于如何启动线程的代码
标签: java android multithreading bluetooth sleep