Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect bluetooth SPP disconnection without using packets

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();
    }
 }
like image 748
Lukeyb Avatar asked Oct 29 '22 04:10

Lukeyb


1 Answers

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
    }
}
like image 81
Samuel Peter Avatar answered Nov 09 '22 06:11

Samuel Peter