I have declared an intent filter for USB_ACCESSORY_ATTACHED in the constructor of a MyDialogFragment and registered/unregistered it in the fragment's onResume and onPause methods. MyReceiver extends BroadcastReceiver in an inner class to receive the USB_ACCESSORY_ATTACHED intent. See following code:
public class MyDialogFragment extends DialogFragment {
private Context context;
private IntentFilter usbIntentFilter;
private MyReceiver myReceiver;
MyDialogFragment(Context context) {
usbIntentFilter = new IntentFilter(UsbManager.ACTION_USB_ACCESSORY_ATTACHED);
myReceiver = new myReceiver();
this.context = context;
}
@Override
public void onResume() {
super.onResume();
// Register broadcast receiver
context.registerReceiver(myReceiver, usbIntentFilter);
}
@Override
public void onPause() {
super.onPause();
// Unregister broadcast receiver
context.unregisterReceiver(myReceiver);
}
class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("MyApp","Called USB receiver");
}
}
}
However, the onReceive method of MyReceiver never gets called when I attach a USB accessory. Furthermore, when I change the intent to
usbIntentFilter = new IntentFilter(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
the onReceive method of MyReceiver does get called. So my question is: why does it work when I detach the accessory, but not when I attach the accessory?
So it appears that USB_ACESSORY_ATTACHED intent never actually gets through to the activity, see SO question :
Android 3.1 USB-Host - BroadcastReceiver does not receive USB_DEVICE_ATTACHED
You have to work with the onResume method that is called indirectly by USB_ACCESSORY_ATTACHED. I have to say, this isn't clear in the Android documentation, and I question its implementation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With