Intent Filter not calling onReceive for USB_ACCESSORY_ATTACHED

匿名 (未验证) 提交于 2019-12-03 02:16:02

问题:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!