I've run into a wall using the usb api. I am trying to use a broadcast receiver to receive the intent ACTION_USB_DEVICE_ATTACHED but it will not.
To clarify I had this working great through the manifest but that created a new activity (and added to the back stack). I found this undesirable, especially given the nature of my app (a terminal).
My guess is that the device-filter xml metadata needs adding to the intent filter but I have no idea how.
Any feedback is welcome!
EDIT - some code. Here is the juicy part from the manifest. Note that the intent filter is commented out in order to have a dynamically registered BroadcastReceiver pick up the intent (I assume you have 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 hooks up my receiver
//register for attachment
IntentFilter attachedFilter = new IntentFilter(UsbManager.ACTION_USB_DEVICE_ATTACHED);
registerReceiver(mUsbAttachedReceiver, attachedFilter);
This is the BroadcastReceiver declaration
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 a receiver in the manifest as I'm not totally sure about the practice to use there (the receiver exists seperate to any activity). Am I right in thinking the receiver will run as long as the application is running or is it foreground only even if declared in manifest? Any literature on this is appreciated.
I have since skirted around this issue by given the activity a 'singleTop' launchmode and implementing onNewIntent(). That gives me the behaviour I wanted while also allowing launches without the activity running (using manifest). This was my ultimate goal. However, I really wish to understand this behaviour and remain highly interested in a solution!
FURTHER EDIT: My debug device is a Samsung Galaxy S3. I have not changed the ROM.