android read设置超时时间,在Android中的BluetoothSocket inputstream.read()中实现超时
你可以這樣做:
InputStream in = someBluetoothSocket.getInputStream();
int timeout = 0;
int maxTimeout = 8; // leads to a timeout of 2 seconds
int available = 0;
while((available = in.available()) == 0 && timeout < maxTimeout) {
timeout++;
// throws interrupted exception
Thread.sleep(250);
}
byte[] read = new byte[available];
in.read(read);
這樣,您最初可以從具有特定超時的流中讀取.如果你想在任何閱讀時間實現超時,你可以嘗試這樣的事情:
Thread readThread = new ReadThread(); // being a thread you use to read from an InputStream
try {
synchronized (readThread) {
// edit: start readThread here
readThread.start();
readThread.wait(timeOutInMilliSeconds);
}
catch (InterruptedException e) {}
使用此方法,您可能需要某種事件處理程序來通知您的應用程序,如果該線程實際讀取了輸入流中的內容.
我希望有所幫助!
– – 編輯:
我沒有使用任何處理程序實現了一個示例.
Socket s = new Socket("localhost", 8080);
final InputStream in = s.getInputStream();
Thread readThread = new Thread(new Runnable() {
public void run() {
int read = 0;
try {
while((read = in.read()) >= 0) {
System.out.println(new String(new byte[]{ (byte) read }));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
synchronized (readThread) {
readThread.start();
try {
readThread.wait(2000);
if(readThread.isAlive()) {
// probably really not good practice!
in.close();
System.out.println("Timeout exceeded!");
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
總結
以上是生活随笔為你收集整理的android read设置超时时间,在Android中的BluetoothSocket inputstream.read()中实现超时的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 容器精华问答 | Docker和虚拟机有
- 下一篇: 乐乐花上征信吗