即时通讯使用此代码我想在应用程序退出时断开蓝牙,但当应用程序退出时,套接字仍然连接到蓝牙设备。我认为"取消"线程在代码中不起作用。我该怎么做才能断开它?在此先感谢
public class ConnectToBluetooth implements Runnable{
private BluetoothDevice btShield;
private BluetoothSocket mySocket = null;
private UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
public ConnectToBluetooth(BluetoothDevice bluetoothShield) {
btShield = bluetoothShield;
try{
mySocket = btShield.createRfcommSocketToServiceRecord(uuid);
}catch(IOException createSocketException){
//Problem with creating a socket
}
}
@Override
public void run() {
/* Cancel discovery on Bluetooth Adapter to prevent slow connection */
bluetooth.cancelDiscovery();
try{
/*Connect to the bluetoothShield through the Socket. This will block
until it succeeds or throws an IOException */
mySocket.connect();
} catch (IOException connectException){
try{
mySocket.close(); //try to close the socket
}catch(IOException closeException){
}
return;
}
}
/* Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mySocket.close();
} catch (IOException e){
}
}
}