I have an app which interacts with a USB OTG device:
- When a USB device connects, a helper activity is started to display the Android confirmation dialog. This is done via an
IntentFilterin the manifest. - The helper activity starts a service is started by sending it an app-specific intent.
- The service’s
onCreate()method populates anIntentFilter, adding the actions to which the service should react when running, includingUsbManager.ACTION_USB_DEVICE_DETACHED. Adding extra debug output tells me the method runs when I expect it to, i.e. theIntentFilteris populated when I register the receiver. - The service’s
onStartCommand()method calls an internal method which registers theBroadcastReceiverfor the intent filter (if the service was started with the start intent, and has the necessary permissions—else the service terminates). - When the receiver receives
UsbManager.ACTION_USB_DEVICE_DETACHEDand the device reported is the one that is currently connected, it stops the service. - There is also a main activity, which is not involved in handling the USB device.
- The service also gets called for other reasons, notably when a charger is connected. In this case the service looks for a Bluetooth device (if a USB device is already connected, indicated by a member of the service instance being non-null, this is skipped and the service exits).
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?
BroadcastReceiveris not being registered. - Martin ZeitlerregisterReceiver()gets called; I need to add extra code to ensure theIntentFilteris populated as desired. - user149408