我正在使用带键盘的设备,并且想无限期地监听按键。我在inputStream.read()
循环中有一个while(true)
,该循环工作...直到我希望停止读取输入。那时,我将停留在inputStream.read()
,直到输入其他内容。
try {
// Call api and get input stream
Call<ResponseBody> call = clockUserAPI.getKeyboardStream();
Response<ResponseBody> response = call.execute();
inputStream = response.body().byteStream();
// Continuously run <<<<<<<<<<<<<<<<<
while (keepReading) {
// Read from input stream
Log.w(TAG, "Reading from input stream");
final byte[] buffer = new byte[256];
int bytesRead = bytesRead = inputStream.read(buffer, 0, buffer.length);
// Process response
Log.v(TAG, bytesRead + " bytes read. Now precessing");
String fullResponse = new String(buffer, 0, bytesRead, StandardCharsets.UTF_8);
processResponse(fullResponse);
try { Thread.sleep(100); } catch (InterruptedException e1) { e1.printStackTrace(); }
} catch (Exception e) {
e.printStackTrace();
// Sleep for a sec
Log.d(TAG, "Keyboard thread interrupted");
try { Thread.sleep(1000); } catch (InterruptedException e1) { e1.printStackTrace(); }
// Something happened. Close the input stream
if (inputStream != null) {
try {
Log.v(TAG, "Closing input stream");
inputStream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
Thread.sleep(500);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
inputStream = null;
}
}
}
关于输入流和连续输入的最佳实践是什么?
最佳答案
如果我理解正确,那么您的问题是停止从InputStream
读取。您可以使用易失性布尔变量停止读取:
class PollingRunnable implements Runnable{
private static final String TAG = PollingRunnable.class.getSimpleName();
private InputStream inputStream;
private volatile boolean shouldKeepPolling = true;
public PollingRunnable(InputStream inputStream) {
this.inputStream = inputStream;
}
public void stopPolling() {
shouldKeepPolling = false;
}
@Override
public void run() {
while (shouldKeepPolling) {
final byte[] buffer = new byte[256];
int bytesRead = 0;
try {
bytesRead = inputStream.read(buffer, 0, buffer.length);
String fullResponse = new String(buffer, 0, bytesRead, StandardCharsets.UTF_8);
//Process response
} catch (IOException e) {
Log.e(TAG, "Exception while polling input stream! ", e);
} finally {
if(inputStream != null) {
try {
inputStream.close();
} catch (IOException e1) {
Log.e(TAG, "Exception while closing input stream! ", e1);
}
}
}
}
}
}
要停止轮询,请使用:
// Supply you input stream here
PollingRunnable pollingRunnable = new PollingRunnable(inputStream);
new Thread(pollingRunnable).start();
//To stop polling
pollingRunnable.stopPolling();
关于java - 使输入流正确的方法一直读取直到程序关闭?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43458104/