(1) Two ways to register Broadcastreceiver
When we create a broadcast receiver class that inherits from Broadcastreceiver, in order to register in the program, the first way to register is XML, in the Mainfest registration file to register, the registered XML code is as follows
<application android:allowbackup= "true" android:icon= "@drawable/ic_launcher" android:label= "@ String/app_name " android:theme=" @style/apptheme "> <activity android:name=". Mainactivity " android:label=" @string/app_name "> <intent-filter> <action android:name=" Android.intent.action.MAIN "/> <category android:name=" Android.intent.category.LAUNCHER "/> </intent-filter> </activity> <receiver android:name= "Myreceiver" > < intent-filter> <action android:name= "Dengchaoqun. Reciever "/> </intent-filter> </receiver> </application>
And then send the broadcast in the program
Intent intent=new Intent ("Dengchaoqun. Reciever ");
Sendbroadcast (Intent);
(2) dynamic registration via Java code
PrivateButton btnstart; PrivateButton Btnstop; Privatebroadcastreceiver Receiver; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); //Dynamic Registration BordcastreceverReceiver=NewMyreceiver (); Intentfilter Filter=NewIntentfilter ("Myreceiver"); Registerreceiver (receiver, filter); Btnstart=(Button) Findviewbyid (R.id.button1); Btnstop=(Button) Findviewbyid (R.id.button2); Btnstart.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {//static mode /*Intent intent=new Intent ("Dengchaoqun. Reciever "); Sendbroadcast (intent);*/Intent Intent=NewIntent ("Myreceiver"); Sendbroadcast (Intent); } }); Btnstop.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {unregisterreceiver (receiver); } }); }
(3) Destruction Unregisterreciever (receiver) of the recipient's object;
(4) In the recipient object
@Override
public void OnReceive (context context, Intent Intent) {
Toast.maketext (context, "test", "a"). Show ();
}
Time-consuming operations cannot be performed in the Onreceiver, and if there is a time-consuming operation, the thread must be called, or the intent startup services will complete
Android four components of the Broadcastreceiver