我已经USB_ACCESSORY_ATTACHED
在 a 的构造函数中声明了一个意图过滤器,MyDialogFragment
并在片段onResume
和onPause
方法中注册/取消注册它。在内部类中MyReceiver
扩展以接收意图。请参见以下代码:BroadcastReceiver
USB_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
确实被调用。所以我的问题是:为什么当我分离附件时它可以工作,但当我连接附件时却不行?