3

我已经USB_ACCESSORY_ATTACHED在 a 的构造函数中声明了一个意图过滤器,MyDialogFragment并在片段onResumeonPause方法中注册/取消注册它。在内部类中MyReceiver扩展以接收意图。请参见以下代码:BroadcastReceiverUSB_ACCESSORY_ATTACHED

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");

        }
     }
}

但是,当我连接 USB 附件时onReceive,永远不会调用该方法。MyReceiver此外,当我将意图更改为

usbIntentFilter = new IntentFilter(UsbManager.ACTION_USB_ACCESSORY_DETACHED);

onReceive方法MyReceiver确实被调用。所以我的问题是:为什么当我分离附件时它可以工作,但当我连接附件时却不行?

4

1 回答 1

1

因此,意图似乎USB_ACESSORY_ATTACHED从未真正进入活动,请参阅 SO question:

Android 3.1 USB-Host - BroadcastReceiver 不接收 USB_DEVICE_ATTACHED

您必须使用onResume间接调用的方法USB_ACCESSORY_ATTACHED。我不得不说,这在 Android 文档中并不清楚,我质疑它的实现。

于 2013-11-04T18:47:13.963 回答