Intent Filter not calling onReceive for USB_ACCESS

2020-02-13 01:58发布

问题:

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?

回答1:

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.