Android, Broadcas Introduction

Source: Internet
Author: User

What is broadcast

In Android, broadcast is a widely used mechanism for transferring information between applications. Let's use the radio station to make an analogy. We usually use radio radios like this: a lot of different radio stations send their content at certain frequencies, and our users just need to tune the frequency to be the same as the radio station to listen to their content. The broadcasting mechanism in Android is similar to this.

The content on the radio is voice, and the broadcast content that we are sending in Android is a intent. This intent can carry the data we want to transmit.

The radio sends the content via a high-powered transmitter, and in Android it is sent through the Sendbroadcast method (the very image name).

The
user accepts the contents of the radio station by adjusting to the specific radio frequency. And in Android to accept the broadcast content is by registering a broadcastreceiver to receive. Only the action that sends the broadcast and the action that receives the broadcast are the recipients who can accept the broadcast.
What's the use of broadcasting? In fact, in what is the first sentence of the broadcast it has been explained what is the use of broadcasting. By the way, the general point is to transfer the data. The specific point is that: 1. The data transfer and sharing between different programs is realized, as long as the recipient who is the same as the one sending the broadcast will be able to accept the broadcast. Typical applications are Android-brought text messages, phone calls, and so on, so as long as we're broadcasting their action, we'll be able to receive their data for some processing. For example, intercept the system SMS, intercept the harassment phone and so on 2. The role of a notification, such as in the service to notify the main program, update the main program UI and so on. Because the service does not have an interface, the control in the main program cannot be obtained directly, so that we can only implement a broadcast recipient in the main program to accept data and notifications sent by the service. Implement broadcast

Now we're going to implement a simple broadcast program. Android provides two forms of registered broadcast recipients, which are dynamically registered in the program and specified in the XML. The difference between them is that the scope of the action is different, the recipient of the program dynamic registration is only valid while the program is running, and the recipient of the XML registration will work regardless of whether your program has started. The method of dynamic registration in the program is introduced first.

Dynamic Registration method

We have set up three buttons in the program, namely "Register broadcast", "Unregister" and "Send Broadcast". Then each button sets the Click event to complete the broadcast demo.

The simplest project establishment process and the establishment of button events I'm not going to be a little wordy here. Download the demo source below. See the implementation of the three buttons directly.

The first is the button event code that registers the broadcast:

123456789101112131415161718192021222324252627 privateReceiveBroadCast receiveBroadCast;  //广播实例publicclassRegisteLinster implements OnClickListener{        @Override        publicvoidonClick(View view)        {            // 注册广播接收            receiveBroadCast = newReceiveBroadCast();            IntentFilter filter = newIntentFilter();            filter.addAction(flag);    //只有持有相同的action的接受者才能接收此广播            registerReceiver(receiveBroadCast, filter);        }}publicclassReceiveBroadCast extends BroadcastReceiver{         @Override        publicvoidonReceive(Context context, Intent intent)        {            //得到广播中得到的数据,并显示出来            String message = intent.getStringExtra("data");            txtShow.setText(message);        }}

First we implement a Receivebroadcast class, which inherits the Broadcastreceiver and implements the OnReceive method, so that this method is executed when the broadcast is received. Note that we used the Filter.addaction method to add a filter when registering the broadcast. Without this sentence, it would be a good idea to listen to radio stations without telling us how often they were received.

To see how to unregister, the program no longer receives this type of broadcast.

123456789 public classUnregisteLinster implements OnClickListener{        @Override        publicvoidonClick(View arg0)        {            unregisterReceiver(receiveBroadCast);        }}

What do you think? is not super simple Ah, it is the broadcast class above us to pass in the example of the line. Register now, cancel the registration is good, the remaining how to send. Look at the code:

1234567891011 publicclassSendBroadCastListener implements OnClickListener{        @Override        publicvoidonClick(View arg0)        {            Intent intent = newIntent();  //Itent就是我们要发送的内容            intent.putExtra("data", "this is data from broadcast "+Calendar.getInstance().get(Calendar.SECOND));               intent.setAction(flag);   //设置你这个广播的action,只有和这个action一样的接受者才能接受者才能接收广播            sendBroadcast(intent);   //发送广播        }}

Every sentence has been commented, do not let me say it again. It's clear at first sight. Now, run the program to see the effect. Register first, and then each time you send a broadcast the text will change once, indicating that the broadcast has been received. Press Cancel to register and you can see that the Send button has not received the broadcast.

Configuration file Mode

The difference between configuration and dynamic registration has been stated above, and this approach is appropriate for your program that requires long-term monitoring of a broadcast situation, such as monitoring a user's text messages. The registration method is relatively simple, the equivalent of the above code as long as the part of the receipt of the line. It is important to note, however, that registering a broadcast through a configuration file requires inheriting the Broadreceiver in a separate class, and the inner class is useless. So we created a new Broadcastreceivebyxml class and inherited the Broadreceive. The code is as follows:

12345678910 publicclassbroadCastReceiveByXml extends BroadcastReceiver{    @Override    publicvoidonReceive(Context arg0, Intent arg1)    {        Log.d("qlf", "broadcast receive by xml");    //因为不在主UI下,不好使用控件,所以我们这里打印到LOG里面查看效果    }}

Then we add the code after the <activity></activity> node in androidmanifest:

123456 < Code class= "CSharp Plain" ><receiver android:name= " Com.qlf.broadCast.broadCastReceiveByXml " > &NBSP;&NBSP;&NBSP;&NBSP; <INTENT-FILTER> &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP; <action android:name= "Com.qlf.broadCastFlag" > &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP; </ACTION> &NBSP;&NBSP;&NBSP;&NBSP; </INTENT-FILTER> </RECEIVER>

The android:name in receiver is the class in our program that receives the broadcast. The following intent-filter is similar to the one we talked about, and this action is the flag above. Now we run the program and find that the same functionality can be implemented. The results of the operation are as follows:

In addition to using our own to send broadcasts, Android has built in many broadcasts. For example, when we mentioned above, Android sends a broadcast with the action named "Android.provider.Telephony.SMS_RECEIVED". This time, if we want to accept this broadcast, just set the action in the configuration file to the string above to receive the message. Android includes a number of other broadcast action, interested students to search on the internet has. This is no longer an example.

Android, Broadcas Introduction

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.