Broadcast

Broadcast: In Android, Broadcast is a widely used mechanism for transmitting information between applications. Let's take the radio station as an example. We usually use radios like this: many different radio stations transmit their content on a specific frequency, and our users only need to tune the frequency to the same frequency as the radio station to listen to their content. The broadcast mechanism in Android is similar to this. Android broadcast is divided into two aspects: broadcast sender and broadcast receiver. Usually, BroadcastReceiver refers to the broadcast receiver (broadcast receiver).

From the perspective of the implementation principle, the broadcast in Android uses the observer pattern, a message-based publish/subscribe event model. Therefore, from an implementation point of view, broadcasting in Android decouples the sender and receiver of the broadcast to a great extent, making the system easier to integrate and easier to expand. The main points of the specific implementation process are roughly summarized as follows:

1. The broadcast receiver BroadcastReceiver registers with AMS (Activity Manager Service) through the Binder mechanism;

2. The broadcast sender sends the broadcast to the AMS through the binder mechanism;

3. AMS finds the BroadcastReceiver that meets the corresponding conditions (IntentFilter/Permission, etc.), and sends the broadcast to the corresponding message loop queue of the BroadcastReceiver (usually Activity);

4. The message loop execution gets this broadcast and calls back the onReceive() method in BroadcastReceiver.

Now let's implement a simple broadcast program. Android provides two forms of registering broadcast receivers, which are dynamically registered in the program and specified in xml. The difference between them is that the scope of action is different. The receiver registered dynamically by the program is only valid during the running process of the program, while the receiver registered in xml will work regardless of whether your program is started or not. First introduce the way of dynamic registration in the program.

 

Case download address: https://github.com/DickyQie/android-four-components

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326290460&siteId=291194637