I have some Bluetooth devices which connect to an Android phone, however I'm having trouble detecting disconnections. The bluetooth devices don't send data packets unless they need to, so it's not an option to use a watchdog on packet reception to detect a disconnect. I've read that you can use the ACLDisconnected broadcast, but this event is never firing for me (I've waited minutes). What is a reliable way to detect a disconnection in Android 6?
Here is my AclDisconnect registering code:
_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);
And the callback (which doesn't fire on disconnect)
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();
}
}
I don't know about Xamarin, but in plain Android / Java this is typically done by catching the IOException
that is thrown by the InputStream when the stream is closed. For example:
// 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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With