Get intent ACTION_USB_DEVICE_ATTACHED via code

I ran into a wall using usb api. I am trying to use a broadcast receiver to get the intent ACTION_USB_DEVICE_ATTACHED, but it will not.

To clarify, I did a great job with this manifest, but created a new activity (and added to the back stack). I found this undesirable, especially considering the nature of my application (terminal).

My guess is that the xml filter device metadata needs to be added to the intent filter, but I have no idea how to do this.

Any feedback is appreciated!

EDIT is some code. Here is the juicy part from the manifest. Note that the intent filter is commented out so that the dynamically registered BroadcastReceiver takes the intent (I suppose you need to).

//<intent-filter> // <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" /> // <category android:name="android.intent.category.DEFAULT" /> //</intent-filter> <meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" android:resource="@xml/device_filter"/> 

Here is the code that connects my receiver

 //register for attachment IntentFilter attachedFilter = new IntentFilter(UsbManager.ACTION_USB_DEVICE_ATTACHED); registerReceiver(mUsbAttachedReceiver, attachedFilter); 

This is a BroadcastReceiver announcement.

 private final BroadcastReceiver mUsbAttachedReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { //BREAKPOINT HERE IS NEVER HIT String action = intent.getAction(); showDebugToast(action); if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) { synchronized(this) { UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE); if (device != null){ getDevicePermission(device); } } } } }; 

I avoided declaring the recipient in the manifest, because I'm not entirely sure that the practice is used there (the recipient exists separately for any activity). Do I think that the receiver will work as long as the application is launched, or will it be foreground, even if it is declared in the manifest? Any literature on this subject is appreciated.

Since then, I have circumvented this issue by specifying the "singleTop" launchmode action and implementing onNewIntent (). This gives me the behavior that I wanted, and also allowed me to run without activity (using the manifest). That was my ultimate goal. However, I really want to understand this behavior and remain very interested in a solution!

FURTHER EDITION: My debugging device is the Samsung Galaxy S3. I have not changed the ROM.

+4
source share
1 answer

yes, you need to add metadata with Activity as:

 <meta-data android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED" android:resource="@xml/accessory_filter" /> 

accessory_filter:

 <resources> <usb-accessory manufacturer="Acme, Inc" model="Whiz Banger" version="7.0" /> </resources> 

see this Android developer blog Bright Idea: Android Open Accessories

0
source

All Articles