Android蓝牙连接SPP后断开会出现IOException异常

dztai dztai 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
Android蓝牙连接SPP后断开会出现IOException异常, log如下

E/BluetoothSocket(5549): java.io.IOException: Operation Canceled
E/BluetoothSocket(5549): at android.bluetooth.BluetoothSocket.readNative(Native Method)
E/BluetoothSocket(5549): at android.bluetooth.BluetoothSocket.read(BluetoothSocket.java:386)
E/BluetoothSocket(5549): at android.bluetooth.BluetoothInputStream.read(BluetoothInputStream.java:96)
E/BluetoothSocket(5549): at java.io.InputStream.read(InputStream.java:163)
E/BluetoothSocket(5549): at com.adayome.hudsettingdemo.bt.BluetoothConnection$5.run(BluetoothConnection.java:335)

整个逻辑是这样的,连接SPP后,开启一个线程一直在read数据,

private class readThread extends Thread {
public void run() {

byte[] buffer = new byte[1024];
int bytes;
InputStream mmInStream = null;
try {
mmInStream = GlobalVariables.sSocket.getInputStream();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while (!isInterrupted()) {
try {
// Read from the InputStream
if ((bytes = mmInStream.read(buffer)) > 0) {

byte[] buf_data = new byte[bytes];
for (int i = 0; i < bytes; i++) {
buf_data[i] = buffer[i];
}
String s = new String(buf_data);
LogUtils.i("readThread---------------2 s = " + s);
if (s.trim().equals("exit"))
break;
Message msg = new Message();
msg.obj = s;
msg.what = 1;
LinkDetectedHandler.sendMessage(msg);
}
} catch (IOException e) {
try {
mmInStream.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
break;
}
}
}
}

在退出时会中断这个线程和关闭相应的Socket

if (mReadThread != null) {
mReadThread.interrupt();
mReadThread = null;
}

if (GlobalVariables.sSocket != null) {
try {
InputStream in = GlobalVariables.sSocket.getInputStream();
OutputStream ou = GlobalVariables.sSocket.getOutputStream();

ou.close();
in.close();
GlobalVariables.sSocket.close();

} catch (IOException e) {
LogUtils.debugLog(e);
}

GlobalVariables.sSocket = null;
}

此时就会报上面的 java.io.IOException: Operation Canceled
各位大神有什么好的解决办法吗?
有什么办法可以中止I/O阻塞的线程?或是让read返回-1?
...全文
评论 3
收藏 已收藏
分享
返回顶部
dztai
Android 80,490 成员 91,375 内容