我有一些连接到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();
}
}
答案 0 :(得分:2)
我不了解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
}
}
答案 1 :(得分:0)
BluetoothDevice.ActionAclDisconnected确实不可靠,检测断开连接的唯一可靠方法是捕获IOException,就像之前的回答状态一样。
因此,您必须开发一种“ping”机制,每隔X次发送一次数据。