I tried the first method, the result is feasible, I am new in onCreate directly a broadcast and then rewrite the onReceive, registered in onResume Filter and radio receiver, cancellation receiver in onDestory,
Then I want to have for the broadcast receiver on a single class, called UsbBroadcastReceiver, then rewrite the onReceive inside, in the onCreate fragments new class - this class, no other and cancellation of change, but such writing, I can't receive the USB insert the radio, I wonder whether I am creating a class and use of the broadcast time is what's the problem? Don't know whether someone give me answer that question, thank you
onReceive method
Public class UsbBroadcastReceiver extends BroadcastReceiver {
Private static final String TAG="UsbBroadcastReceiver";
@ Override
Public void onReceive (Context Context, Intent Intent) {
The d (TAG, "onReceive:" + intent. GetAction ());
String intentAction=intent. GetAction ();
If (UsbManager. ACTION_USB_DEVICE_ATTACHED. Equals (intentAction)) {
The d (TAG, "onReceive, radio reception to insert the USB device intent");
}
}
}
Filter registered broadcasting method, this method will be invoked in onResume
Private void setFilter () {
IntentFilter filter=new IntentFilter ();
Filter. AddAction (ACTION_USB_PERMISSION);
Filter. AddAction (UsbManager. ACTION_USB_DEVICE_ATTACHED);
Filter. AddAction (UsbManager. ACTION_USB_DEVICE_DETACHED);
GetActivity (). GetApplicationContext (.) registerReceiver (mUsbReceiver, filter);
}
New my radio receiver in onCreate
@ Override
Public void onCreate (@ Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MUsbReceiver=new UsbBroadcastReceiver ();
The d (TAG, "onCreate: first create.");
}
CodePudding user response:
Do you confirm to use the same Context objectCodePudding user response:
Thank you, your answer is very interesting, in fact, I think I should also is the problem, but my understanding of the context is not enough in-depth,If I create a broadcastreceiver in fragments, it is my current use of fragments of the context, but in this case, I even in I went to the new current in the fragments of my custom radio receiver, but can't accurately passed on context,
Also, if I have two fragments, at the same time to create the radio receiver, that they are to deal with global broadcast (as long as the filter) through me, that I how to distinguish the two radio receiver?