Broadcast Mechanism in Android Development

Source: Internet
Author: User
Broadcast Mechanism in Android Development

/*

* Broadcast mechanism for Android Development

* Beijing Android Club group: 167839253

* Created on: 2012-7-31

* Author: blueeagle

* Email: liujiaxiang@gmail.com

*/

Overview

In Android, after some operations are completed, a broadcast will be sent, for example, a text message or a phone call. If a program receives the broadcast, the corresponding processing will be performed. This broadcast is somewhat similar to the radio broadcast in our traditional sense. It is called Broadcast because it is only responsible for "speaking", regardless of "listening or listening", that is, no matter how the receiver handles it. In addition, broadcast can be received by more than one application, and of course it may not be received by any application.

What is broadcast receiver?

Broadcastreceiver is the third component in the Android Application. The broadcast reciver and event processing mechanisms are similar. The difference is that the event processing mechanism is at the application component level. For example, the onclicklistener event of a button can only be processed in one application. The broadcast event processing mechanism is system-level. Different applications can process broadcast events.

How to Use broadcast Receiver

You can build an intent object and call the sendbroadcast () method to send the broadcast. Event acceptance is implemented by a Class inherited from broadcastreceiver. Override the onreceiver () method after inheritance to respond to events in this method. Of course, you cannot forget to register broadcastreceiver in the androidmanifest. xml file.

Generally, classes inherited from broadcastreceiver are defined according to our own needs. This custom class is used to process broadcast events in Android. That is to say, the broadcast in the Android operating system is received by the broadcastreceiver class. After receiving the message, the onreceive () method in this class will be called for processing. So, in the Android system, there are a lot of broadcasts. How can we determine what types of broadcasts a single receiver is responsible? By the way. This is to write the androidmanifest. xml file. We need to register in androidmanifest. xml and register the handler to the application. The intent-filter determines the type of events that the receiver should receive.

For the onreceive method, once the method is returned. The system will think that the object has been completed. This is no longer an active state.

Follow the instructions above. The Code is as follows:

Public class broadcastreceivertest extends activity {private button mybutton; @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); mybutton = (button) findviewbyid (R. id. mybutton); mybutton. setonclicklistener (newbutton. onclicklistener () {@ override public void onclick (view v) {intent myintent = new intent (); myintent. setaction (myintent. action_edit); broadcastreceivertest. this. sendbroadcast (myintent); // send broadcast }});}}

You need to write the broadcastreceiver class. The Code is as follows:

public class ReceiverTest extends BroadcastReceiver {    public ReceiverTest(){       System.out.println("ReceiverTest");    }    @Override    public void onReceive(Context arg0, Intent arg1) {       System.out.println("onReceive");          }}

The Code registered in androidmanifest. XML is as follows:

   <receiver           android:label="@string/app_name"           android:name=".ReceiverTest" >            <intent-filter >                <action android:name="android.intent.action.EDIT" />            </intent-filter>        </receiver>

After compilation, we will get the following results on the console:

If you press the button twice in a row, the button appears twice. :

 

In the preceding example, the action type of intent is action_edit, And the handler type registered in androidmanifest. XML is also edit. <action
Android: Name ="Android. Intent. Action. Edit"/>

, Which indicates that the two actions are matched. After the sendbroadcast method is executed, the receiver of the edit type can receive the message. If the type match is successful, the system will generate the receiver object and call the onreceiver method. As mentioned above, a new receiver object is generated every time a broadcast is received. After processing, this object will not be used any more.

Method for registering a broadcast Receiver

Broadcastreceiver can listen to broadcast objects. Generally, intent is used for broadcast. Then, for the purpose of listening, broadcastreceiver must be registered. There are two registration methods:

 

Register in the androidmanifest. xml file:

Note that, if I am using androidmanifest. if you register a broadcastreceiver in an XML file, the broadcastreceiver is active and can receive broadcast events regardless of whether the application of the broadcastreceiver is running or disabled. For example, applications such as receiving short messages and displaying battery power consumption. We need to listen to these statuses in the STANDBY state, but we cannot open the application all the time.

Register in the application code:

When we need to update the status of the controls in the activity, we need to register them in the application code. At this time, if we register them in androidmanifest. XML, it is not appropriate. This is because the broadcastreceiver should be disabled only when the activity is visible and invisible. Otherwise, various resources will be wasted. Therefore, you need to register in the application code. Register broadcastreceiver after the activity is started, and cancel the registration after the activity is invisible.

The registration code is very simple: registerreceiver (filter );

Correspondingly, the code for canceling registration is unregisterreciver (handler ER );

The receiver parameter indicates a broadcastreceiver object (thebroadcastreceiver to handle the broadcast .); filter indicates an intent-filter object (selectsthe intent broadcasts to be encoded ed .), with us in androidmanifest. the intent-filter tag used in the XML file has the same effect. We will discuss how to create an intent-filter object later.

The following example uses the mobile phone to receive information. The Code is as follows:

Public class broadcastreceivertest extends activity {private button myregisterbtn; private button myunregisterbtn; private smsreceiver mymessagereceiver; Private Static final string sms_action = "android. provider. telephony. sms_received "; Private Static final string edit_action =" android. intent. action. edit "; @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancest Ate); setcontentview (R. layout. main); myregisterbtn = (button) findviewbyid (R. id. registerbtn); myunregisterbtn = (button) findviewbyid (R. id. unregisterbtn); myregisterbtn. setonclicklistener (newmyregisterlistener (); myunregisterbtn. setonclicklistener (newmyunregisterlistener ();} class myregisterlistener implements onclicklistener {@ override public void onclick (view v) {mymessagereceiver = new smsrec Eiver (); // generate a broadreceiver object intentfilter myfilter = new intentfilter (); // generate an intentfilter object myfilter. addaction (sms_action); // Add an action broadcastreceivertest for intentfilter. this. registerreceiver (mymessagereceiver, myfilter);} // the entire operation completes the registration of broadcastreceiver.} Class myunregisterlistener implements onclicklistener {@ override public void onclick (view v) {broadcastreceivertest. This. unregisterreceiver (region); // unregister the broadcastreceiver object in the system }}}

The code is simple, that is, two buttons are defined. One is to bind broadcastreceiver to the application, and the other is to unbind broadcastreceiver from the application. Correspondingly, we also need to write the receiver class. To facilitate the test, we only write a print output in the receiver class. The Code is as follows:

public class SMSReceiver extends BroadcastReceiver {    @Override    public void onReceive(Context context, Intent intent) {       System.out.println("onReceivestart");        }}

Of course, we registered the broadcastreceiver in the application, so we don't have to register it again in the androidmanifest. xml file. (Readers can try to register in the androidmanifest. xml file to see what will happen .) Run the program, click the register button, and then use ddms to send a text message to the simulator. :

After clicking the send button, check the console and you will find that "onreceive start" has been printed, as shown in:

This means that the receiver receives a broadcast after filtering events such as sending information. Now, the two registration methods of broadcastreceiver are finished.

After talking about these two methods, readers may have a series of questions. That's why my action is Android. provider. telephony. when sms_received is sent, the corresponding receiver can receive the broadcast. If my action is not, will the broadcast be sent? How can I determine what operations a specific action corresponds? In order to be received by the broadcast receiver. How many built-in actions are involved in the Android system? Can we customize an action? If so, how can we define it?


First, let's take a look at the built-in Android broadcast actions.

 

Android built-in broadcast actions

The Android platform has many built-in actions to help developers monitor various events on their mobile phones. The following is an example of the built-in broadcastaction:

Android. Intent. Action. battery_changed

The charging status or the battery power changes.

Android. Intent. Action. screen_on

The screen has been opened.

Android. Intent. Action. package_removed

An application package is deleted from the device.

Android. Intent. Action. time_tick

The current time has changed (normal time elapsed)

 

To query the complete list of broadcastaction, you can find the intent class in the help documentation of the official SDK. In the definition of constants, you can find the information starting with broadcast action. For example, we can find a constant of the string type: action_battery_low. The subsequent explanation is starting with "broadcast action.

String action_battery_low broadcast action: indicates low batterycondition on the device.

Generally, the built-in broadcast action provided by the Android operating system is sufficient. Of course, you can also customize the broadcast action.

Custom broadcast action

Custom broadcast actions is actually a custom String constant. Then broadcast the constant and receive the constant again. The following code is used to describe the custom broadcastaction. At the same time, the broadcastreceiver and the broadcast project are split into two projects to describe how to process the broadcast receipt between different projects. The Code is as follows:

 

Public class mybroadcast extends activity {public static final string new_broadcast = "com. todd. new_broadcast ";/* The static constant string can be customized by yourself, representing the Custom Action */@ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); button mybutton = (button) findviewbyid (R. id. mybutton); mybutton. setonclicklistener (newbutton. onclicklistener () {public void o Nclick (view v) {intent myintent = new intent (new_broadcast); myintent. putextra ("MSG", "sweet potato, I'm a potato! "); Myintent. setaction (new_broadcast); sendbroadcast (myintent );}});}}

Only one button needs to be defined in the XML file

<Button Android: Id = "@ + ID/mybutton" Android: layout_width = "fill_parent" Android: layout_height = "wrap_content" Android: text = "Send broadcast"/>

Then a project is created to receive the data broadcast from the broadcast project. The Code is as follows:

public class MyReceiver extends BroadcastReceiver {    /** Calledwhen the activity is first created. */    @Override    public void onReceive(Context context, Intent intent) {       // TODO Auto-generatedmethod stub       String message = intent.getExtras().getString("MSG");       Toast.makeText(context, message, Toast.LENGTH_LONG).show();       System.out.println(message);    }}

It is not complete yet. A registration process is required. The registration process is to let the receiving project know which intent data I want to receive.

Register the following in androidmanifest. xml:

        <receiver android:name=".MyReceiver">            <intent-filter>                <action android:name="com.todd.NEW_BROADCAST" />            </intent-filter>        </receiver>

In this way"Com. Todd. new_broadcast"The action is registered to the receiving project. In this case, the receiving project is complete.

But is it over? No. If the broadcast project does not have any problems after compilation at this time, but the receiving project may encounter errors, such as classcast errors. This is because, when compiling and receiving a project, we did not give the receiving project an activity to display the received information. Therefore, we need to define an activity. The Code is as follows:

public class IntentRes extends Activity {    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);    }}

Of course, in the corresponding androidmanifest. xml file, you must modify it:

        <activity android:name=".IntentRes"                  android:label="@string/app_name">            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>

Now, broadcasting and receiving are completed. They are located in different projects.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.