[Android] broadcast of four Android components
preface
This chapter studies Android broadcast events, which are used to send broadcasts or monitor broadcasts.
1. What is broadcasting
Broadcast is one of the four components in android. It is a mechanism to spread data (Intent) between components. The sender and receiver of broadcasting do not need to know each other's existence in advance. The advantage of this is that the various components of the system can be loosely coupled together, so that the system has a high degree of scalability and is easy to integrate with other systems.
Broadcast has the following characteristics:
- The life cycle of the broadcast receiver is very short. It is created when the broadcast is received and destroyed after the onReceive() method is completed
- Do not do some time-consuming work in the broadcast receiver, otherwise the Application No Response error dialog box will pop up
- It's better not to create a sub thread in the broadcast receiver to do time-consuming work, because after the broadcast receiver is destroyed, the process becomes an empty process, which is easy to be killed by the system
- The time-consuming work is best done in the service (service is one of the four components that will be discussed in the next chapter)
It should be noted that after Android 8.0 (that is, API26), most static broadcast events are limited. It is recommended to use dynamic broadcast in the official documents!
Broadcasting can be divided into the following types:
- System broadcasting: Android has built-in multiple system broadcasting: as long as it involves the basic operation of the mobile phone (such as power on, network state change, taking photos, etc.), it will send out corresponding broadcasting waves, and each broadcasting has a specific Intent - Filter (including specific action s)
- Ordinary broadcast: it is characterized by complete asynchrony. It is sent by sendBroadcast() method and received by onReceive method. Message passing efficiency is high, but the execution order of all receivers is uncertain. The disadvantage is that the receiver cannot pass the processing result to the next receiver, and cannot terminate the propagation of broadcast Intent until there is no matching receiver to broadcast.
- Ordered broadcast: it is sent by sendOrderedBroadcast. It has the following characteristics:
- The broadcast is received according to the priority of the receiver. The priority is declared in the priority in intentFilter, - 1000 to 1000. The higher the value, the higher the priority,
- The continuous propagation of the broadcast can be terminated, and the receiver can modify the content of intent.
- The receiving order of the same level is random, and the lower level is received later
- It can cut off the continuous propagation of the broadcast, and the high-level broadcast receiver can decide when to cut off after receiving the broadcast. Can handle broadcast
1. Dynamically register broadcasts and unregister
Let's take the simplest example - monitoring the current power. We monitor a broadcast of the current power, which belongs to one of the system broadcasts.
How to achieve it?
We use the method of dynamic broadcasting:
- First, create an IntentFilter object and set its action to the broadcast event we want to listen to (here is the broadcast of Intent.ACTION_BATTERY_CHANGED system)
- Secondly, create a class that inherits BroadcastReceiver, as follows: BatteryLevelReceiver, and override onReceive method
- Finally, we call the registerReceiver method of activity to transmit our broadcast receiver object and intent filter object, and then complete the broadcast receiving registration.
- It should be noted that when the current activity is destroy ed, we need to cancel the registration to prevent memory leakage!
public class BroadcastActivity extends AppCompatActivity { private static final String TAG = "BroadcastActivity"; private BatteryLevelReceiver receiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_broadcast); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED); receiver = new BatteryLevelReceiver(); // Broadcast registration this.registerReceiver(receiver,intentFilter); } private class BatteryLevelReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); Log.d(TAG,"received action == "+action); int state = intent.getIntExtra(BatteryManager.EXTRA_LEVEL,0); Log.d(TAG,"Current power == "+state); } } @Override protected void onDestroy() { super.onDestroy(); // Cancel broadcast registration if (receiver != null) { this.unregisterReceiver(receiver); } } }
We use the setting of battery power in the simulator for simulation:
The effect after calling is as follows:
3. Send custom broadcast and receive
The custom broadcast here is also an ordinary broadcast. Let's write one ourselves!
Pay attention to details, Android 8 To dynamically register broadcasts after 0, use the registerReceiver() method
xml page file
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".study.test.BroadcastActivity" android:orientation="vertical"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Please enter the content to be broadcast!" android:id="@+id/et_broadcastContent"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/bt_broadcastTransmissionBtn" android:text="Click to send a broadcast~" /> </LinearLayout>
BroadcastActivity class
public class BroadcastActivity extends AppCompatActivity { private static final String TAG = "BroadcastActivity"; private Button btn; private EditText content; private MessageReceiver messageReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_broadcast); initView(); registerMessageBroadcast(); } private void initView() { btn = this.findViewById(R.id.bt_broadcastTransmissionBtn); content = this.findViewById(R.id.et_broadcastContent); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { sendBroadcastMessage(v); } }); } private void sendBroadcastMessage(View v) { // Click and call to send the broadcast String s = content.getText().toString(); Intent intent = new Intent(); intent.setAction("top.woodwhale.test.SEND_MSG"); intent.putExtra("content",s); // Execute sending method this.sendBroadcast(intent); } private void registerMessageBroadcast() { // Register your own SEND_MSG broadcast IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction("top.woodwhale.test.SEND_MSG"); messageReceiver = new MessageReceiver(); // Execute registration method this.registerReceiver(messageReceiver,intentFilter); } class MessageReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // If send is received_ MSG broadcast if (intent.getAction().equals("top.woodwhale.test.SEND_MSG")) { String content = intent.getStringExtra("content"); Log.d(TAG,"receive SEND_MSG Broadcast, content:"+ content); } } } @Override protected void onDestroy() { super.onDestroy(); // Don't forget to cancel your registration~ if (messageReceiver != null) { this.unregisterReceiver(messageReceiver); } } }
The effect is as follows:
4. Orderly broadcasting
Orderly broadcasting uses less. Oh, I'm too lazy to write. I have time to make up.
As for the grant of broadcast permission, set the permission in manifest
In the second overloaded method of sendBroadcast, the second parameter is receiverPermission, that is, broadcast receiving permission