-1
我有藍牙插座有問題,我發現了一個IOException
告訴我:Socket Closed
拋出IOException異常,當我試圖關閉的BluetoothSocket
唯一的例外發生在這裏:
} catch (IOException e) {
try {
inputStream.close();
socket.close();
} catch (IOException e1) {
Log.e("CLOSE: ", e.getMessage());
}
Log.e("IO FROM RUN: ", e.getMessage());
}
相關codesnippet :
class AcceptThread extends Thread {
/**
* Tag that will appear in the log.
*/
private final String ACCEPT_TAG = AcceptThread.class.getName();
/**
* The bluetooth server socket.
*/
private final BluetoothServerSocket mServerSocket;
public AcceptThread() {
BluetoothServerSocket tmp = null;
try {
tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(
"Bluetooth Service", UUID.fromString(defaultUUID));
} catch (IOException e) {
e.printStackTrace();
}
mServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
while (true) {
try {
Log.i(ACCEPT_TAG, "Listening for a connection...");
socket = mServerSocket.accept();
Log.i(ACCEPT_TAG, "Connected to "
+ socket.getRemoteDevice().getName());
} catch (IOException e) {
break;
}
// If a connection was accepted
if (socket != null) {
ReadInputThread inputThread = new ReadInputThread(socket);
inputThread.start();
}
}
}
/** Will cancel the listening socket, and cause the thread to finish */
public void cancel() {
try {
mServerSocket.close();
} catch (IOException e) {
}
}
class ReadInputThread extends Thread {
BluetoothSocket socket;
InputStream inputStream;
public ReadInputThread(BluetoothSocket socket) {
InputStream tempIs = null;
try {
this.socket = socket;
tempIs = socket.getInputStream();
} catch (IOException e) {
Log.e("IO: ", e.getMessage());
}
inputStream = tempIs;
}
public void run() {
Log.i(TAG, "BEGIN ReadInputThread");
final byte[] buffer = new byte[1024];
int bytes;
while (true) {
try {
bytes = inputStream.read(buffer);
if(inputStream.available() < 0) {
inputStream.close();
socket.close();
}
Log.i("BYTE COUNT: ", Integer.toString(bytes));
Log.i("BYTES: ", new String(buffer));
} catch (IOException e) {
try {
inputStream.close();
socket.close();
} catch (IOException e1) {
Log.e("CLOSE: ", e.getMessage());
}
Log.e("IO FROM RUN: ", e.getMessage());
}
}
}
}
有誰能給我一個關於如何解決這個問題的提示嗎?謝謝!
應用程序讀取輸入內容,或者至少輸出一些字節到LogCat。我嘗試在'socket.close'之後放置一個'break;',但仍然發生異常。不管怎麼說,還是要謝謝你。 –
突破可能會突破if語句。 標記您的while循環,例如 myWhileLoop: while(true){ 然後你的socket.close()添加一個 break myWhileLoop; – athor