我现在有两台通过蓝牙连接的设备。之后,我断开了客户端设备上的蓝牙连接,此客户端设备中的广播接收器可以检测到断开连接,然后将其切换回上一个活动。像这样:
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Message msg = Message.obtain();
String action = intent.getAction();
if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
try {
Log.i("Disconnecting3", "Disconectinggg....");
Intent intent1 = new Intent(Main3Activity.this, MainActivity.class);
startActivity(intent1);
} catch (Exception e) {
e.printStackTrace();
}
}
}
};
无论如何,在我的其他设备上,即服务器设备,该设备 CAN NOT 检测到断开连接,尽管蓝牙插座已关闭!服务器设备中的广播接收器无法检测到断开连接。仅供参考,下面的代码将显示当客户端设备断开连接时我如何关闭服务器设备上的蓝牙套接字。
private boolean CONTINUE_READ_WRITE;
CONTINUE_READ_WRITE = true;
public void run() {
try {
while (CONTINUE_READ_WRITE) {
try {
// Read from the InputStream.
numBytes = mmInStream.read(mmBuffer);
// Send the obtained bytes to the UI activity.
Message readMsg = handleSeacrh.obtainMessage(MessageConstants.MESSAGE_READ, numBytes, -1, mmBuffer);
readMsg.sendToTarget();
} catch (IOException e) {
//nothing();
CloseConnection closeConnection = new CloseConnection();
closeConnection.start();
break;
}
}
} catch (Exception e) {
// Log.d(TAG, "Input stream was disconnected", e);
}
}
public void cancel() {
try {
Log.i("TAG", "Trying to close the socket");
CONTINUE_READ_WRITE = false;
mBluetoothSocket.close();
mmBluetoothSocket.close();
Log.i("TAG", "I thinked its still closing");
} catch (IOException e) {
Log.e("TAG", "Could not close the connect socket", e);
}
}
因此,当客户端设备发生断开连接时,while(CONTINUE_READ_WRITE)..循环将中断循环并启动新的Thread。像这样:
private class CloseConnection extends Thread {
public void run(){
Log.i("Running","Runinnggggg");
try {
mmInStream.close();
mmOutStream.close();
bluetoothDataTransmission.cancel();
Log.i("Interrupted","InteruppteDDDD");
} catch (IOException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:0)
好吧,我找到了一个解决方案,只需要添加这行代码
intentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);