连接到两个设备时使用 BroadcastReceiver 处理丢失的蓝牙连接问题

Issue handling lost Bluetooth connections using BroadcastReceiver when connected to two devices

我有以下代码来处理丢失的蓝牙连接。

public class BluetoothReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();


        if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
            //call method to cancel connection thread
        }
    }
}

但是,我有另一个应用在后台使用蓝牙连接到另一台设备 运行。如果我失去与该设备的连接,我也会失去与此应用程序中设备的连接。

我想知道,有什么办法可以防止这种情况发生吗?

如所述here,您可以使用 intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE) 从意图中获取设备实例如果设备不是您感兴趣的设备,请不要调用:

  //call method to cancel connection thread