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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…