Explain the broadcastreceiver component in Android

Broadcastreceiver means "broadcast receiver". It is used to receive broadcasts from systems and applications.

In Android, broadcast is a widely used mechanism for transmitting information between applications. Broadcastreceiver is a kind of component that filters, accepts and responds to the sent broadcast.

The following describes in detail how to send a broadcast and how to filter the reception using a broadcastreceiver:

(1) First, load the information to be sent and the information used for filtering (such as action and category) into an intent object where the information needs to be sent, and then send the intent object by broadcasting by calling the sendorderbroadcast() or sendstickybroadcast() methods.

(2) After the intent is sent, all registered broadcastreceivers will check whether the intentfilter at the time of registration matches the sent intent. If it matches, the onreceive() method of broadcastreceiver will be called. Therefore, when we define a broadcastreceiver, we need to implement the onReceive () method.

There are two ways to register broadcastreceiver

Static registration: register with tag life in androidmanifest.xml, and set filter with tag in the tag.

Dynamic registration: use intentfilter to dynamically register a broadcast in the code

In addition, it should be noted that when we use dynamic registration, if the activity or service is destroyed without deregistration, the system will report an exception to prompt us whether we have forgotten to deregister, so we need to deregister in ondestroy() method. Generally, register in OnStart and cancel unregisterreceiver in onstop:

Specify broadcast target action: intent intent = new intent (actionstring);

And messages can be carried through intent: intent.putextra ("MSG", "Hi, I sent messages through broadcast");

Send broadcast message: context. Sendbroadcast (intent)

In dynamic registration, you can encapsulate the inherited class of broadcastreceiver, add constructor and broadcastreceiver registration

Case demonstration of broadcastreceiver

First, we create a class mybroadcastreceiver to inherit broadcastreceiver: here, we rewrite a method to accept the broadcast intention and match:

Here are constants: defined as follows:

(1) Next, we will use it through "dynamic registration":

(2) For static registration, add the following to the list file:

(2-1) we can use the code:

Normal broadcast

Ordinary broadcast is completely asynchronous for multiple receivers. Usually, each receiver can receive the broadcast without waiting, and the receivers will not affect each other. For this broadcast, the receiver cannot terminate the broadcast, that is, the receiving action of other receivers cannot be blocked. To verify the above conclusion, we create three new broadcastreceivers to demonstrate the process. The codes of firstreceiver, secondreceiver and thirdreceiver are as follows:

Then click the send button again to send a broadcast, and the console prints as follows:

It seems that these three receivers have received this broadcast. We will slightly modify the three receivers and add the following code in the last line of onReceive method to try to terminate the broadcast:

Click the send button again, and we will find that the three receivers in the console still print their own logs, indicating that the receiver cannot terminate the broadcast.

Ordered broadcast

Ordered broadcasting is special. It is only sent to the receiver with higher priority each time, and then transmitted by the receiver with higher priority to the receiver with lower priority. The receiver with higher priority has the ability to terminate the broadcasting. In order to demonstrate the process of orderly broadcasting, we modify the codes of the above three receivers as follows:

We note that in both firstreceiver and secondreceiver, setresultextras is used to set a bundle object as a result set object and transfer it to the next receiver. In this way, recipients with low priority can use getresultextras to obtain the latest processed information set. After the code is changed, we need to register the broadcast addresses for the three recipients. Let's modify the androidmainfest.xml file:

We can see that the three recipients now have an Android: priority attribute, which decreases in turn. The range of this attribute is - 1000 to 1000. The higher the value, the higher the priority. Now, we need to modify the broadcast sending code as follows:

Note that a permission parameter is required when sending an ordered broadcast using the sendorderedbroadcast method. If it is null, it means that the receiver is not required to declare the specified permission. If it is not null, it means that the receiver needs to declare the specified permission to receive this broadcast. This is done from the perspective of security. For example, the SMS of the system is in the form of orderly broadcasting. An application may have the function of intercepting spam SMS. When the SMS arrives, it can receive the SMS broadcast first and terminate the broadcast transmission if necessary. Such a software must declare the permission to receive SMS. Therefore, we define a permission in androidmainfest.xml:

Then declare that this permission is used:

If you don't understand anything about this part, please refer to an article I wrote before: Android statement and permission. Then we click the send button to send a broadcast. The console prints as follows:

We can see that the reception is in order. The first and second add their own tags in the result set and pass them to the recipients with low priority. Since it is a sequential transfer, try to terminate the transfer and see the effect. We modify the code of firstreceiver and add the following code in the last line of onReceive:

Then run the program again and the console prints as follows:

This time, only the first receiver executed, and the other two failed to execute, because the broadcast was terminated by the first receiver. The above is the introduction of broadcastreceiver. Next, I will give several common examples to deepen your understanding and application of Broadcasting:

1. Startup service

We often have such applications, such as message push service, which need to realize the function of startup. To realize this function, we can subscribe to the broadcast of "startup completion" of the system. After receiving this broadcast, we can start our own services. Let's take a look at the specific implementation of bootcompletereceiver and msgpushservice:

Then we need to configure relevant information in androidmanifest.xml:

We see that bootcompletereceiver registers the boot broadcast address "Android. Intent. Action. Boot_completed". From a security point of view, the system requires that it must declare the permission to receive the boot broadcast, so we declare to use the following permissions: after the above steps, we complete the boot function and run the application on the simulator, Then restart the simulator and the console prints as follows:

If we look at the running services, we will find that msgpushservice is already running.

2. Change of network status

On some occasions, such as when users browse network information, the network is suddenly disconnected. We should timely remind users that the network has been disconnected. To realize this function, we can receive a broadcast of network state change. When the connection state changes to the disconnected state, the system will send a broadcast. After we receive it, we will make corresponding operations through the network state. Here's how to realize this function:

Register the recipient's information again:

Because we use APIs related to network status in isnetworkavailable method, we need to declare relevant permissions. The following is the corresponding permission declaration:

We can test it, such as turning off WiFi to see what effect it has.

3. Power change

If we read the software, it may be full screen reading. At this time, users will not see the remaining power, and we can provide them with power information. To do this, we need to receive a broadcast of power change and obtain the percentage information. This sounds very simple. Let's achieve the following:

Then you can register the broadcast address information:

Of course, sometimes we need to get the power immediately rather than wait for the broadcast of power changes. For example, when the reading software is turned on, the battery power is displayed immediately. We can get it in the following ways:

The above is the whole content of this article. I hope it will be helpful to your study.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>