Android 在不使用数据包的情况下检测蓝牙SPP断开

Android 在不使用数据包的情况下检测蓝牙SPP断开,android,xamarin,bluetooth,Android,Xamarin,Bluetooth,我有一些蓝牙设备可以连接到Android手机,但是我在检测断开连接时遇到了问题。蓝牙设备不发送数据包,除非他们需要,所以它不是一个选项,使用数据包接收监视器来检测断开连接。我已经读到你可以使用ACL断开连接的广播,但是这个事件永远不会为我触发(我已经等了几分钟)。在Android 6中,检测断开连接的可靠方法是什么 这是我的注册代码: _filter = new IntentFilter(); _filter.AddAction(BluetoothDevice.ActionFound); _fi

我有一些蓝牙设备可以连接到Android手机,但是我在检测断开连接时遇到了问题。蓝牙设备不发送数据包,除非他们需要,所以它不是一个选项,使用数据包接收监视器来检测断开连接。我已经读到你可以使用ACL断开连接的广播,但是这个事件永远不会为我触发(我已经等了几分钟)。在Android 6中,检测断开连接的可靠方法是什么

这是我的注册代码:

_filter = new IntentFilter();
_filter.AddAction(BluetoothDevice.ActionFound);
_filter.AddAction(BluetoothDevice.ActionBondStateChanged);
_filter.AddAction(BluetoothAdapter.ActionDiscoveryStarted);
_filter.AddAction(BluetoothDevice.ActionAclDisconnected);
_filter.AddAction(BluetoothDevice.ActionAclDisconnectRequested);
context.RegisterReceiver(_bluetoothDeviceReceiver, _filter);
以及回调(在断开连接时不会触发)


我不知道Xamarin,但在普通的Android/Java中,这通常是通过捕获InputStream关闭时抛出的
IOException
来完成的。例如:

// In your listening thread
InputStream inputStream = socket.getInputStream();
while (true) {
    try {
        int nextByte = inputStream.read();
        // Do something with it
    } catch (IOException e) {
        // Here you know that you are disconnected
    }
}

BluetoothDevice.ActionAclDisconnected确实不可靠,检测断开连接的唯一可靠方法是捕获IOException,就像前面的回答状态一样


因此,您必须开发一种“ping”机制,在该机制中,数据每X次发送一次。

您是否有BluetoothGattCallback的回调?Bluetooth Gatt与低能耗相关。SPP代表串行端口协议,它是蓝牙经典的一部分。实际上,您甚至不需要接收任何数据,只需阻塞read()调用,直到断开连接。这在Xamarin中有效。我会补充说,从我的测试,这是唯一的方式做到这一点。您必须通过_Stream=_socket.InputStream作为InputStreamInvoker从BluetoothSocket获取流对象;
// In your listening thread
InputStream inputStream = socket.getInputStream();
while (true) {
    try {
        int nextByte = inputStream.read();
        // Do something with it
    } catch (IOException e) {
        // Here you know that you are disconnected
    }
}