我正在尝试从输入流中读取数据,但如果程序在 X 时间内没有接收到数据,我想终止尝试并返回 -1
。我之前使用的是 Thread.sleep( X )
但后来意识到这是一种完全不正确的方法。如果有人有任何想法,请告诉我。这是我从输入流中读取的代码...
try {
// Read from the InputStream
bytes = mmInStream.read(buffer, 0, length);
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(MainMenu.MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
// Start the service over to restart listening mode
BluetoothService.this.start();
//break;
}
最佳答案
您可以使用 Future做这个。
首先,您需要一个将作为“ future ”值返回的类:
public class ReadResult {
public final int size;
public final byte[] buffer;
public ReadResult(int size, byte[] buffer) {
this.size = size;
this.buffer = buffer;
}
}
然后需要使用executor服务,使用get(long timeout, TimeUnit unit)像这样:
ExecutorService service = Executors.newSingleThreadExecutor();
Future<ReadResult> future = service.submit(new Callable<ReadResult>() {
@Override
public ReadResult call() throws Exception {
bytes = mInStream.read(buffer, 0, length);
return new ReadResult(bytes, buffer);
}
});
ReadResult result = null;
try {
result = future.get(10, TimeUnit.SECONDS);
} catch (InterruptedException e1) {
// Thread was interrupted
e1.printStackTrace();
} catch (ExecutionException e1) {
// Something bad happened during reading
e1.printStackTrace();
} catch (TimeoutException e1) {
// read timeout
e1.printStackTrace();
}
if (result != null) {
// here you can use it
}
这样你就可以实现你的目标。请注意,最好将 Callable 类子类化,该类将接受输入流作为构造函数参数,然后使用类变量。
关于android - 仅等待输入 X 时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11887950/