Broadcast Broadcast in Android View Manual

The fourth Broadcast

Broadcast is one of the four major components of Android. It is an information transmission mechanism. Through broadcasting, we can monitor the information transmitted between ourselves, the Android system, or three-party applications. Just like the frequency band of a walkie-talkie, under the same channel, the broadcast mechanism can be used to communicate with each other. Clever use of the broadcast mechanism can enable our applications to achieve unexpected functions.

overview

As one of the four major components of Android, broadcasting is an important bridge for us to communicate with the system. For example, changes in system power, lock screen, date change, plugging in an external power source, etc., will let the system send out in the form of broadcasts. When our application requirements need to receive this information, we can use broadcasting to achieve it. In addition to communicating with the system, we can also use broadcasting and other applications, or communicate with ourselves, which is essentially a messaging method based on AMS (Activity Manager Service) for centralized management.

broadcast registration

insert image description here

Creation of broadcast receivers

To use broadcast, we first need to create a broadcast receiver to process the received broadcast information and content , as follows, just inherit android.content.BroadcastReceiver and implement its onReceive method.

import android.content.BroadcastReceiver;  
import android.content.Context;  
import android.content.Intent;  
import android.util.Log;  
  
public class MyReceiver extends BroadcastReceiver {
    
      
      
    private static final String TAG = "MyReceiver";  
      
    @Override  
    public void onReceive(Context context, Intent intent) {
    
      
    	String message = intent.getStringExtra("message");
        Log.i(TAG, "onReceive"+message);  
    }  
    
} 

In the onReceive method, we can get the data in the Intent from the broadcast. Of course, after creating the class, we need to register the broadcast accordingly, just like joining a group. Only after adding this group can we receive news to this group .

static registration

By configuring in the AndroidManifest.xml file, we can achieve static registration. The action (android.intent.action.BOOT_COMPLETED) here is the address of the boot broadcast, which is equivalent to the group id. Only with this action can we receive the corresponding Broadcast messages, of course, there can be more than one action here, and we can also pass in custom types of actions. Among them, the static registration is a resident type, that is to say, when the application is closed, if there is a broadcast message, the broadcast we registered will also be called by the system to run automatically .

<receiver android:name=".MyReceiver">  
   <intent-filter>  
       <action android:name="android.intent.action.BOOT_COMPLETED"/>  
       <action android:name="android.intent.action.MY_BROADCAST"/>  
       <category android:name="android.intent.category.DEFAULT" />  
   </intent-filter>  
</receiver>  

However, many broadcasts in the system currently do not support static registration, so you must understand when using static registration. Some of the following commonly used broadcast actions do not support it.

broadcast action describe
android.intent.action.ACTION_TIME_TICK The system sends out this broadcast every minute
android.intent.action.SCREEN_ON Broadcast after the screen is lit
android.intent.action.SCREEN_OFF Broadcast after the screen is turned off
android.intent.action.BATTERY_CHANGED The state of charge, or the power of the battery has changed//The state of charge of the battery
android.intent.action.CONFIGURATION_CHANGED The broadcast sent when the device's current settings are changed includes the interface language, device orientation, etc.
dynamic registration

In addition to the configuration method, we can also dynamically register the broadcast in the code. Similar to the static registration, we also need to specify the broadcast address and register, as shown in the following code:

MyReceiver receiver = new MyReceiver();  
IntentFilter filter = new IntentFilter();  
filter.addAction("android.intent.action.MY_BROADCAST"); 
filter.addAction("android.intent.action.SCREEN_ON"); 
registerReceiver(receiver, filter);  

Among them, registerReceiver is a method in the android.content.ContextWrapper class . When we are not using it in Activity and Service (both of which inherit ContextWrapper), we need to pass an object that inherits ContextWrapper to execute. The difference from static registration is that we need to monitor the class that calls the registration method, and unregister it when it is about to be destroyed, otherwise the system will throw an exception to tell us whether the broadcast has not been canceled. The removal operation is as follows:

@Override  
protected void onDestroy() {
    
      
    super.onDestroy();  
    unregisterReceiver(receiver);  
} 

Dynamic registration is not permanent, because we will not be able to receive information after the broadcast is released.

broadcast send

sendBroadcast is also a method in the android.content.ContextWrapper class. We stuff the information we need to pass into the intent and specify its action (passed in the instance Intent class method here), so that we can send a broadcast .

Intent intent = new Intent("android.intent.action.MY_BROADCAST");  
intent.putExtra("message", "it's a Broadcast!");  
sendBroadcast(intent);  

broadcast type

The form of broadcast transmission is currently mainly divided into Ordered Broadcast and Normal Broadcast. In addition to these two types, there are also deprecated Sticky Broadcast and local messages that are actually delivered through Handler. Broadcasting (because it does not belong to broadcasting in essence, this article will not introduce it).

general broadcast

Ordinary broadcasts are completely asynchronous for multiple receivers. Usually, each receiver can receive the broadcast without waiting , and the receivers will not affect each other. For this kind of broadcast, the receiver cannot terminate the broadcast, that is, it cannot prevent other receivers from receiving actions. Many broadcasts in the system are delivered in this way.
insert image description here
When we need to send a normal broadcast, just press and call the send method:

Intent intent = new Intent("android.intent.action.MY_BROADCAST");  
intent.putExtra("message", "it's a Broadcast!");  
sendBroadcast(intent);  
orderly broadcast

Ordered broadcast is special, it is only sent to higher priority receivers each time, and then propagated by higher priority receivers to lower priority receivers, and higher priority receivers have the ability to terminate this broadcast . Among them, the receiver can modify the data to be sent, and both modification and addition are possible, which means that after the priority receiver modifies the data, the data accepted by the next receiver is the one that has been modified by the previous receiver. The text messages in the system broadcast are orderly. We can intercept the text messages by intercepting them. Of course, this requires obtaining the corresponding permissions.
insert image description here
When we need to send ordered broadcasts, just press and call the send method:

Intent intent = new Intent("android.intent.action.MY_BROADCAST");  
intent.putExtra("message", "it's a Broadcast!");  
sendOrderedBroadcast(intent,null);

Among them, the priority of ordered broadcast, the larger the number, the higher the priority (value range: -1000~10000), can be configured as follows:

  • Dynamic Registration Setting Priority
MyReceiver receiver = new MyReceiver();  
IntentFilter filter = new IntentFilter();  
filter.setPriority(99);//设置优先级
filter.addAction("android.intent.action.MY_BROADCAST"); 
registerReceiver(receiver, filter);  
  • Static registration setting priority
<receiver
            android:name=".MyReceiver"
            android:priority="59" 
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="not_order_broadcast" />
            </intent-filter>
        </receiver>
        <!--
        priority:这个属性设置优先级
        exported:这个属性用于指示该服务是否能够被其他应用程序组件调用或跟它交互。
         如果设置为true,则能够被调用或交互,否则不能。设置为false时,
        只有同一个应用程序的组件或带有相同用户ID的应用程序才能启动或绑定该服务
        -->
  • The data received by the broadcast can be modified and transmitted, or directly intercepted and no longer transmitted
public class MyReceiver extends BroadcastReceiver {
    
    
    public MyReceiver() {
    
    
    }

    @Override
    public void onReceive(Context context, Intent intent) {
    
    
        if ("MY_BROADCAST".equals(intent.getAction())){
    
    
        	String message = intent.getStringExtra("message");
        	if(message.equal("Next")){
    
    
        		//修改内容
	            Bundle bundle = new Bundle();
	            bundle.putString("message", "内容有变动");
	          	setResultExtras(bundle);
            }else{
    
    
            	//阻断广播的发送到下一个
				abortBroadcast();
			}
        }
    }
}
sticky broadcast

The message of sticky broadcast always exists in the message container of the system after it is sent, waiting for the corresponding processor to process it. If there is no processor to process the message, it will always be in the waiting state in the message container. If the Receiver of sticky broadcast is destroyed , then the message data will be automatically received at the next rebuild. It should be noted that as long as the sticky broadcast is not removed, it will always be in the memory. This may be the reason. The sticky broadcast is currently deprecated, and there are security risks. After the broadcast is sent, the broadcast (Intent) just sent will be saved, so that the receiver can continue to use the broadcast just now after registering the Receiver. If multiple sticky broadcasts of the same Action are sent before the receiver's registration is completed, only one broadcast of the Action will be received after the registration is completed, and the content of the message is the content of the last broadcast. The broadcast sent when the system network state changes is a sticky broadcast.

insert image description here

Sending sticky broadcasts requires the following permissions

<uses-permission android:name="android.permission.BROADCAST_STICKY" />

When we need to send ordered broadcasts, just press and call the send method:

Intent intent = new Intent("android.intent.action.MY_BROADCAST");  
intent.putExtra("message", "it's a Broadcast!");  
sendStickyBroadcast(intent,null);

tips

1. Reasons why some broadcasts cannot be registered statically

  • Improve system efficiency : Some broadcast behaviors often occur in the Android system, such as screen switching, and broadcasts occur every minute. If most programs listen, it will greatly slow down the entire system, so Android does not encourage us to monitor these broadcasts in the background.
  • Because of the priority issue of ordered broadcast. During static registration, the priority of the system is higher than that of the application, and the system prevents the downward propagation of the broadcast. And because in Android's broadcast mechanism, the priority of dynamic registration is higher than that of static registration . Therefore, dynamic registration is used instead of static registration.
  • Because it stays in the background , it may affect the security of the system. Like some rogue software that keeps starting up and then provides a payment interface to extort money, many of them are implemented by using the broadcast mechanism.

2. It is recommended not to do time-consuming operations in the broadcast.
The response of the program (Responsive) is monitored by the two system services of the Activity Manager (Activity Manager) and the Window Manager (Window Manager). When BroadcastReceive r is not executed within 10 seconds , Android will think that the program is unresponsive , so you cannot do some time-consuming operations in BroadcastReceiver, otherwise an ANR (Application No Response) dialog box will pop up. Among them, the sticky broadcast is not restricted by 10 seconds .

Possible related problems

1. What is the life cycle state of the broadcast?
The life cycle of the broadcast is actually very short. It will be instantiated only when it receives the broadcast, and will be destroyed once the onReceive() method is executed.
2. Can broadcasting be registered multiple times?
Yes, the same broadcast can actually be registered multiple times, so some developers will receive multiple repeated messages at the same time, but actually only send one broadcast, because the broadcast is repeated registered.

The start rule of interview skills

When we express our project experience, it is often easy to miss the key points, and we can answer in an orderly manner through the start rule.
Start rule:
"S"—that is, situation. That is, what is the background and environment in which you participated in certain jobs? For example, school recruitment is based on the company's strategic development and the personnel needs of various departments;

"T" - that is, Task. It is the task or responsibility you undertake in this job. For example, in school recruitment, you are mainly responsible for the planning and publicity of the entire school recruitment activities.

"A" - that is, Action. It is what kind of measures or coping methods you take based on tasks in this job. For example, in school recruitment, you first contact the employment office of each school to confirm by phone, then visit your home to confirm the address of the school recruitment, and finally do the work that needs to be publicized, such as the way of publicity? required materials and so on.

"R"—that is, Result. It is what kind of results you get throughout the work. For example, how many people did you recruit in that school recruitment, and what did you gain and summarize in this school recruitment.

Guess you like

Origin blog.csdn.net/number_cmd9/article/details/125417486