我一直在使用InputStream.read(byte[] b, int off, int len)
方法讀取數據,但現在已經遇到超時問題。我有時會期望讀取超時,並且應該讓程序在超時後進行相應的調整。我試圖實現一個線程,但我真的對線程一無所知,無法讓它工作。我還想補充說,這個線程正在被初始化在另一個線程。我不確定這是什麼意思,但它可能會導致問題。線程捕獲BluetoothSocket InputStream.read()超時
我的初始代碼在我需要閱讀的大多數時間裏都有效,但是每當我期待暫停時,我的程序就會在read()
的通話中凍結並永不超時。當我實現這個新代碼時,我最初的代碼工作的時間現在超時。我使用Thread.wait(500)
,我假設它是500毫秒,但我找不到包括wait()
函數的任何Javadoc。 Here和Here。
我也研究過聲明BluetoothSocket
超時,但我在documentation的任何地方找不到它。
這是我最初的代碼如下所示:
public void run(int length) throws IOException {
buffer = new byte[1024];
try {
bytes = mmInStream.read(buffer, 0, length);
mHandler.obtainMessage(MainMenu.MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
Message msg = mHandler.obtainMessage(MainMenu.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(TOAST, "Device has disconnected from the Bluetooth Module.");
msg.setData(bundle);
mHandler.sendMessage(msg);
connectionLost();
BluetoothService.this.start();
}
這是我試圖實現:
public void run(int length) throws IOException {
buffer = new byte[1024];
length1 = length;
Thread myThread = new Thread(new Runnable() {
public void run() {
try {
bytes = mmInStream.read(buffer, 0, length1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
synchronized (myThread) {
myThread.start();
try {
myThread.wait(500);
if(myThread.isAlive()) {
mmInStream.close();
Log.i("InStream", "Timeout exceeded!");
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
myThread.run();
mHandler.obtainMessage(MainMenu.MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
Message msg = mHandler.obtainMessage(MainMenu.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(TOAST, "Device has disconnected from the Bluetooth Module.");
msg.setData(bundle);
mHandler.sendMessage(msg);
connectionLost();
BluetoothService.this.start();
}
編輯:
所以我試圖重新
buffer = new byte[1024];
bytes = mmInStream.read(buffer, 0, length);
我也做了以下內容:
Scanner scan = new Scanner(new InputStreamReader(mmInStream));
String readIn;
try {
readIn = scan.next();
bytes = 5; // I tried with or without this, since I do not think it matters...
buffer = readIn.getBytes(Charset.forName("US-ASCII"));
}
在我的代碼後來我撥打這個電話....對不起編輯一遍,buf=read(5)
呼叫轉到上面顯示。
byte[] buf = buffer;
write(a);
buf = read(5);
Log.i(TAG, "Before buf[5]");
try {
buf[5] = '\0';
} catch(NullPointerException e) {
return false;
}
當我使用原來的方法,它通過這個buf[5]
調用罰款。但是當我使用新方法時,它在那個位置給了我一個IndexOutOfBoundsException
。我錯過了什麼嗎?預期的輸入應該是CMD\r\n
謝謝,還沒有得到它的工作,但這似乎是要走的路。 – JuiCe
@JuiCe確定NP,使用掃描儀和輸入流閱讀器確實比試圖實現自己的緩衝閱讀器容易得多,它看起來像你正在做的事情(相信我,在那裏做了)... – logray
Can not似乎得到它的工作,我編輯我的帖子,如果你可以花一些時間來檢查出來。謝謝 – JuiCe