gpt4 book ai didi

java - 使输入流继续读取直到程序关闭的正确方法?

转载 作者:行者123 更新时间:2023-12-02 13:23:55 25 4
gpt4 key购买 nike

我正在使用带有键盘的设备,并且我想无限期地监听按键操作。我在 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;
}
}
}

有关输入流和连续输入的最佳实践是什么?

最佳答案

如果我理解正确,您的问题是停止从 InputStream 读取。您可以使用 volatile boolean 变量来停止读取:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com