androidusb-otg

Detect when a USB OTG device disconnects


I have an app which interacts with a USB OTG device:

Now, if I plug in the USB device, I get the confirmation and the service starts, and when I unplug the device, the service stops again. So far, so good.

However, in some cases the service keeps running even after the device is unplugged. I have noticed this always happens when the main activity was open when I connected the device. Logs show me that the service never receives the UsbManager.ACTION_USB_DEVICE_DETACHED broadcast.

While doing further tests (open main activity and navigate away from it before connecting the device), I found evidence that there may be two instances of the service running for some reason.

What is happening here, and how can I reliably detect that the USB device was disconnected?


Solution

  • This behavior appears to be caused by two factors:

    So we need to do two things: