Follow these steps to register broadcastreceiver using code:
1) generate a broadcastreceiver object;
2) generate an intentfilter object;
3) add an action for the intentfilter object;
4) use intentfilter and broadcastreceiver to bind and register a broadcastreceiver to the system. When the System Broadcasts the Action event, the broadcastreceiver is started.
1 first define an activity
Public class broadcastdemoactivity extends activity {private button regbutton, unregbutton; Final Static string smsreceiver = "android. provider. telephony. sms_received "; // The Private mybroadcasted er that receives text messages; // The broadcast receiver @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); initview ();} private void initview () {regbutton = (button) This. findviewbyid (R. id. reg); regbutton. setonclicklistener (New reglistener (); // The broadcast cannot be registered in the internal class, and the error unregbutton = (button) This will be reported. findviewbyid (R. id. reg); unregbutton. setonclicklistener (New reglistener ();} private class reglistener implements view. onclicklistener {public void onclick (view v) {Switch (v. GETID () {case R. id. reg: mybroadreceiver ER = new mybroadreceiver Er (); // This object is used to receive broadcasts. intentfilter filter = new intentfilter (); filter. addaction (smsreceiver); // register a broadcast that receives text messages // register the broadcast receiver in the system broadcastdemoactivity. this. registerreceiver (mybroadizer er, filter); break; case R. id. unreg: // remove broadcastdemoactivity from the system. this. unregisterreceiver (mybroadjavaser); break ;}}}}
2. Define a class that receives broadcasts. This is simple to process and only prints the arrival information of one broadcast.
public class MyBroadReceiver extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {Log.i("MyBroadReceiver", "sms is comming");}}
3. You must declare the permission to receive text messages because you have subscribed to the broadcast for Receiving text messages.
<Manifest xmlns: Android = "http://schemas.android.com/apk/res/android" package = "com. CJF. broadcast "Android: versioncode =" 1 "Android: versionname =" 1.0 "> <uses-SDK Android: minsdkversion =" 8 "/> <uses-Permission Android: name = "android. permission. receive_sms "/> <! -- Receive SMS permission --> <application Android: icon = "@ drawable/ic_launcher" Android: Label = "@ string/app_name"> <activity Android: Name = ". broadcastdemoactivity "Android: Label =" @ string/app_name "> <intent-filter> <action Android: Name =" android. intent. action. main "/> <category Android: Name =" android. intent. category. launcher "/> </intent-filter> </activity> </Application> </manifest>
4. After the code is complete, click the register button and send a text message using the simulator. Logcat prints the message