private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
BluetoothSocket tmp = null;
mmDevice = device;
//从BluetoothDevice中获取Socket
try {
// MY_UUID为UUID串,必须与服务端一致
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
// //取消发现远程设备,这样会降低系统性能
mAdapter.cancelDiscovery();
try {
// 建立连接
mmSocket.connect();
} catch (IOException connectException) {
// 无法连接或连接出错
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
// 在单独的线程中处理事件,如数据传输
manageConnectedSocket(mmSocket);
}
/** 取消连接,关闭Socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
蓝牙通讯2
最新推荐文章于 2021-07-28 18:41:04 发布