【问题标题】:Detect bluetooth SPP disconnection without using packets在不使用数据包的情况下检测蓝牙 SPP 断开连接
【发布时间】:2017-07-27 07:43:08
【问题描述】:

我有一些蓝牙设备可以连接到 Android 手机,但是我无法检测到断开连接。除非需要,否则蓝牙设备不会发送数据包,因此不能选择在数据包接收时使用看门狗来检测断开连接。我读过你可以使用 ACLDisconnected 广播,但这个事件永远不会为我触发(我已经等了几分钟)。在 Android 6 中检测断开连接的可靠方法是什么?

这是我的 AclDisconnect 注册代码:

_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);

还有回调(在断开连接时不会触发)

public override void OnReceive(Context context, Intent intent)
{
    string action = intent.Action;

    if (action == BluetoothDevice.ActionAclDisconnected || action == BluetoothDevice.ActionAclDisconnectRequested)
    {
         Interlocked.CompareExchange(ref Disconnected, null, null)?.Invoke();
    }
 }

【问题讨论】:

  • BluetoothGattCallback 有回调吗?
  • 蓝牙 Gatt 与低能量有关。 SPP 代表串行端口协议,它是蓝牙经典的一部分。

标签: android xamarin bluetooth


【解决方案1】:

我不了解 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
    }
}

【讨论】:

  • 这适用于 Xamarin。我会从我的测试中补充一点,这是唯一的方法。您必须通过 _stream = _socket.InputStream as InputStreamInvoker; 从 BluetoothSocket 获取 Stream 对象
【解决方案2】:

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

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

【讨论】:

  • 其实你甚至不需要接收任何数据,你可以在 read() 调用上阻塞,直到发生断开连接。
猜你喜欢
  • 2018-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-20
  • 1970-01-01
相关资源
最近更新 更多