我在使用键盘的设备上工作,我想无限期地听取按键操作。我在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;
}
}
}
有关输入流和连续输入的最佳做法是什么?
答案 0 :(得分:1)
如果我理解正确,你的问题就是停止阅读InputStream
。您可以使用volatile布尔变量来停止读取:
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();
答案 1 :(得分:0)
最佳做法是在专用线程中执行此操作,以便您可以同时执行其他操作。像
这样的东西InputStream in = ...;
public void readStream() {
byte[] buf = ...;
while (in.read(buf) != -1) {
}
}
public static class MyReader implements Runnable {
public void run() {
readStream();
}
}
new Thread(new MyReader()).start();
这是一个链接类,可以从根本上促进上面解释的内容:https://sourceforge.net/p/tus/code/HEAD/tree/tjacobs/io/DataFetcher.java