Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
609 views
in Technique[技术] by (71.8m points)

android - Intent Filter not calling onReceive for USB_ACCESSORY_ATTACHED

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...