我正在使用鍵盤設備,我想無限期地聽按鍵。我在while(true)
循環中有一個inputStream.read()
,它可以工作,直到我希望輸入停止讀取。此時,我會卡在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;
}
}
}
關於輸入流和連續輸入的最佳實踐是什麼?
看起來像轉換爲Java壞的COBOL程序。當文本框失去焦點時,文本輸入結束。 – danny117
當文本框沒有焦點時,我還需要按鍵進行註冊。 –