Detecting when a USB device is detached on Android
android, android-intent
Solution
USB_DEVICE_DETACHED is a broadcast intent, thus you may want to declare the BroadcastReceiver in manifest with the appropriate intent-filter for detached action, also with meta-data attached. Same goes for USB_ACCESSORY_DETACHED, for who is interested.
Summary: USB_XXX_ATTACHED is an activity intent USB_XXX_DETACHED is a broadcast intent
(where XXX = DEVICE | ACCESSORY)
See: http://developer.android.com/guide/components/intents-filters.html
"There is no overlap within these messaging systems: Broadcast intents are delivered only to broadcast receivers, never to activities or services"
Problem
I've got an Android app that needs to detect when a USB peripheral is attached or detached. It works fine when the peripheral is first attached, but I don't receive any notification (i.e., I don't receive an `Intent` whose action is `ACTION_USB_DEVICE_DETACHED`) when it is subsequently detached. Here's the relevant part of my `AndroidManifest.xml`: ``` <activity android:name=".LauncherActivity"> <intent-filter> <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" /> <action android:name="android.hardware.usb.action.USB_DEVICE_DETACHED" /> </intent-filter> <meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" android:resource="@xml/device_filter" /> <meta-data android:name="android.hardware.usb.action.USB_DEVICE_DETACHED" android:resource="@xml/device_filter" /> </activity> ``` It may also be worth noting that `LauncherActivity` only exists to start a `Service` when the device is attached, and to stop the service when it is detached. In either case, `LauncherActivity` always `finish`es itself immediately. All of this occurs in `LauncherActivity.onCreate`. Any ideas?