Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting when a USB device is detached on Android

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 finishes itself immediately. All of this occurs in LauncherActivity.onCreate.

Any ideas?

like image 302
Michael Avatar asked Apr 02 '13 11:04

Michael


People also ask

What is USB host mode Android?

In USB host mode, the Android-powered device acts as the host. Examples of devices include digital cameras, keyboards, mice, and game controllers. USB devices that are designed for a wide range of applications and environments can still interact with Android applications that can correctly communicate with the device.

How do I change USB settings on Android?

To change USB preferences Drag down the status bar, and then tap Android System next to (USB icon). Tap Tap for more options, and then select an option.

What is accessory mode in Android?

USB accessory mode allows users to connect USB host hardware specifically designed for Android-powered devices. The accessories must adhere to the Android accessory protocol outlined in the Android Accessory Development Kit documentation.


1 Answers

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"

like image 178
Big Avatar answered Oct 24 '22 09:10

Big