蓝牙配对,使用BluetoothSocket.connect()
但是
抛出异常
java.io.IOException: read failed, socket might closed or timeout, read ret: -1"
这是我的代码:
public class BluetoothClientConnThread extends Thread {
// Debugging
private static final String TAG = "BluetoothClientConnThread";
private static final boolean D = true;
// 用于回传消息的Handler
private Handler mmHandler;
// 服务器设备
private BluetoothDevice mmDevice;
// Socket对象
private BluetoothSocket mmSocket;
// SDK版本号
private int sdk_version;
public BluetoothClientConnThread(Handler handler, BluetoothDevice device, int sdk_version) {
this.mmHandler = handler;
this.mmDevice = device;
this.sdk_version = sdk_version;
}
@Override
public void run() {
// 取消发现设备
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
try {
if(D)Log.i(TAG, "Android SDK版本:" + sdk_version);
if(sdk_version >= 10)
{
mmSocket = mmDevice.createInsecureRfcommSocketToServiceRecord(BluetoothTools.MY_UUID);
}
else
{
mmSocket = mmDevice.createRfcommSocketToServiceRecord(BluetoothTools.MY_UUID);
}
mmSocket.connect();
} catch (IOException e) {
try {
mmSocket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
mmHandler.obtainMessage(BluetoothTools.MESSAGE_CONNECT_ERROR).sendToTarget();
return;
}
Message msg = mmHandler.obtainMessage();
msg.what = BluetoothTools.MESSAGE_CONNECT_OK;
msg.obj = mmSocket;
msg.sendToTarget();
}
public void cancel() {
try {
if(sdk_version >= 10)
{
mmSocket = mmDevice.createInsecureRfcommSocketToServiceRecord(BluetoothTools.MY_UUID);
}
else
{
mmSocket = mmDevice.createRfcommSocketToServiceRecord(BluetoothTools.MY_UUID);
}
mmSocket.close();
// 发送关闭连接的消息
mmHandler.obtainMessage(BluetoothTools.MESSAGE_CLOSE_CONNECT).sendToTarget();
} catch (IOException e) {
e.printStackTrace();
}
}
}
任何人都可以解释我收到此错误的原因吗?