After reading this article, you will know the following:
- What is broadcast and its usage scenario
- Android broadcast classification
- Method of registration for broadcast
- Advantages and principles of local broadcasting
- Safety of broadcasting
1.1 What is BroadcastReceiver
- Is one of the four components, mainly used for receiving
app
Transmitted broadcast - Internal communication mechanism: Pass
android
Of the systemBinder
Mechanism.
1.2 Broadcast Classification
1.2.1 Out-of-order Broadcast
- Also known as standard broadcast, it is completely asynchronous
Broadcast execution.
- After a broadcast is sent, all broadcast receivers receive the broadcast message at almost the same time, without any order between them, which makes broadcasting more efficient.
Advantages:
Fully asynchronous, logically any receiver can receive the broadcast, high efficiencyDisadvantages:
The receiver cannot pass the processing to the next receiver and cannot terminate the broadcast.
1.2.2 Orderly Broadcast
-
Is a synchronous broadcast.
-
After a broadcast is sent, only one broadcast receiver can receive the broadcast message at any one time, and the broadcast receiver will continue transmission when its logic is complete.
-
Call the SendOrderedBroadcast() method to send a broadcast, and abortBroadcast() method to intercept the broadcast. You can set the Android :property attribute in the
tag to set the priority. If this attribute is not set, broadcasts are received in the order in which they are registered.
-
Sequential broadcast receivers can transmit data to each other.
-
When a broadcast receiver receives a broadcast, the current broadcast can also pass the data to the next receiver using the setResultData method.
-
The getStringExtra function is used to get the original data of the broadcast. The getResultData method is used to get the data added by the last broadcast receiver. AbortBroadcast method is used to discard the broadcast, so that the broadcast is no longer received by other receivers.
-
conclusion
- Sequential transmission according to the priority of the recipient
A > B > C
, - Each has the right to stop broadcasting, and the next one doesn’t
- Each one can be modified, and the next one gets the result of the previous modification.
1.2.3 Ultimate broadcaster
Context.sendOrderedBroadcast ( intent , receiverPermission , resultReceiver , scheduler , initialCode , initialData , initialExtras )
When we can specifyresultReceiver
Is the ultimate broadcast receiver.- If the higher-priority recipient does not terminate the broadcast, his
onReceive
It will be executed twice - The first is normal reception
- The second is the final reception
- If the one with the highest priority terminates the broadcast, he still receives a final broadcast
1.2.4 Common Scenarios of Broadcast receivers
- Boot up,
sd
Card mounting, low battery, outgoing phone, lock screen, etc - For example, according to the requirements of the product manager, design whether the lock screen decides to pause the music when playing the music.
1.3 Types of BroadcastReceiver
1.3.1 Broadcast as a communication mode between Android components, the following scenarios are used:
Expand on the previous section “Please describe BroadcastReceiver”
APP
Internal message communication.- different
APP
Message communication between. Android
Message communication between the system and APP under certain circumstances.- Broadcast uses the observer pattern, a message-based publish/subscribe event model. Broadcast decouples the sender and receiver of broadcast to a great extent, making the system easy to integrate and expand.
- BroadcastReceiver is a global listener that monitors global broadcast messages and facilitates communication between different components in the system.
- Custom broadcast receivers need to inherit from the base class
BroadcastReceiver
And implement abstract methodsonReceive ( context, intent )
. By default, broadcast receivers also run on the main thread, soonReceiver()
Cannot perform time-consuming operations (no more than10s
), otherwise will produceANR
The problem.onReceiver()
You can use send when interacting with other components in a methodNotification
, start,Service
And so on, it is best not to startActivity
.
1.3.2 System Broadcast
Android
Multiple system broadcasts are built into the system. As long as the basic operations of the mobile phone are involved, corresponding system broadcasts will be basically issued, such as startup, network state change, taking photos, screen closing and opening, power shortage, etc. Within the system, a system broadcast is automatically issued by the system when it occurs at a specific time.- Common System Broadcast
Intent
In theAction
Is the following value:
- SMS reminder:
android.provider.Telephony.SMS_RECEIVED
- Low battery:
ACTION_BATIERY_LOW
- Electric quantity changes:
ACTION_BATTERY_CHANGED
- Power connection:
ACTION_POWER_CO
- from
The Android 7.0
At first, the system will no longer send a broadcastACTION_NEW_PICTURE
和ACTION_NEW_VIDEO
For broadcastingCONNECTIVITY_ACTION
Must be used in coderegisterReceiver
Method to register the receiver inAndroidManifest
The file states that the receiver does not work. - from
The Android 8.0
Start, for most implicit broadcasts, cannot be inAndroidManifest
The receiver is declared in the file.
1.3.3 Local broadcast
- The sender and receiver of a local broadcast belong to the same entity
APP
- Compared with global broadcast, it has the following advantages:
- The rest of the
APP
No local broadcast, no need to worry about data leakage. - other
APP
Impossible to presentAPP
Send local broadcast, do not worry about security holes by othersAPP
To use. - Local broadcast is more efficient than global broadcast transmitted through the system.
Android v4
Provided in the packageLocalBroadcastManager
Class for unified handling of APP local broadcast, used in almost the same way as global broadcast, except to call the register/unregister broadcast receiver and send broadcast read method, need to passLocalBroadcastManager
Of the classgetInstance()
Method to get an instance call.
1.4 Registration mode of BroadcastReceiver
1.4.1 Static Registration
In the androidmanifest.xml file.
<receiver android:name=".MyReceiver" android:exported="true"> <intent-filter> <! - specifies the BroadcastReceiver response by the Intent of the Action - > < Action android: name = "android. Intent. Action. INPUT_METHOD_CHANGED" <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </receiver>Copy the code
- There are two important attributes to focus on:
android: exported
It sets thisBroadcastReceiver
Can you accept otherAPP
Broadcast, when set tofalse
Can only accept components of the same application or have the sameuser ID
The message sent by the application. The default value for this property is set byBroadcastReceiver
In the presence ofIntent-filter
Decided, if there isIntent-filter
, the default value istrue
, or forfalse
。android: permission
If this property is set, only broadcasts sent by broadcast senders with corresponding permissions can be sent by this propertyBroadcastReceiver
Acceptable; If not set, this value grants permissions to the entire application.
1.4.2 Dynamic Registration
- call
Context
的registerReceiver ( BroadcastReceiver receiver , IntentFilter filter )
Method specifies.
1.5 How to register and use BroadcastReceiver in Mainfest and code? (An action is the key)
1.5.1 Registering with a File (Static Broadcast)
-
As long as the app is running, it will receive broadcast messages all the time
-
Presentation:
- a
app
Custom class inheritanceBroadcastReceiver
And then ask me to rewrite itonReveiver
methods
public class MyBroadCastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent Intent) {log. d("MyBroadCastReceiver", "broadcastReceiver "," emsp; + intent.getStringExtra("info") + ""); }}Copy the code
- The manifest file is registered and set
Action
“, simply completing the preparation for acceptance
<receiver android:name=".MyBroadCastReceiver">
<intent-filter>
<action android:name="myBroadcast.action.call"/>
</intent-filter>
</receiver>
Copy the code
1.5.2 Code Registration (Dynamic Broadcast)
-
Broadcasts cannot be received when the registered Activity or Service is destroyed.
-
Presentation:
- At the same time as the broadcast receiver
app
In theMainActivity
Add a register button to register broadcast receivers - Set intent filtering, add
Action
//onCreate Create broadcastReceiver object mReceiver = new MyBroadCastReceiver(); Public void click(View View) {IntentFilter IntentFilter = new IntentFilter(); intentFilter.addAction("myBroadcast.action.call"); registerReceiver(mReceiver, intentFilter); }Copy the code
- Unregister while destroying
@Override
protected void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
Copy the code
1.5.3 In another APP, define a button, set intention, Intention to add message content, Intention to set Action (…) To match, just send a broadcast.
public void click(View view) { Intent intent = new Intent(); Intent. PutExtra ("info", "message content "); intent.setAction("myBroadcast.action.call"); sendBroadcast(intent); }Copy the code
- Running two
app
After:
- Static registration method: another
app
I got it on the radio - Dynamic registration method: own
app
First code registration, then anotherapp
Just broadcast it.
1.6 What is the implementation principle of BroadcastReceiver?
-
Broadcasting in Android uses the observer pattern of design patterns: a message-based publish/subscribe event model.
-
There are three main roles in the model:
- Message subscriber (broadcast receiver)
- Message Publisher (Broadcast publisher)
- Message center (
AMS
, i.e.,Activity Manager Service
)
1.6.1 principle:
- Broadcast receiver through
Binder
Mechanism inAMS
(Activity Manager Service
) register; - The broadcast sender passes
Binder
Mechanism toAMS
Send a broadcast; AMS
According to the request of the broadcast sender, in the registered list, find the appropriateBroadcastReceiver
(Look for evidence:IntentFilter / Permission
);AMS
Send the broadcast toBroadcastReceiver
Corresponding message loop queue;- The broadcast receiver gets the broadcast through the message loop and calls back
onReceive()
Methods. - Note that the broadcast is sent and received asynchronously, and the sender does not care if or when the receiver is received.
1.7 Local Broadcast
- The local broadcast mechanism improves security by allowing outgoing broadcasts to be transmitted only within the application, and the broadcast receiver to accept only broadcasts from the application itself.
- Local broadcasting mainly uses one
LocalBroadcastManager
To manage broadcasts, and provides methods for sending broadcasts and registering broadcast receivers. - Developers just need to implement their own
BroadcastReceiver
Subclass, rewriteonReceive ( Context context, Intetn intent )
Method can. - When other components pass
sendBroadcast()
、sendStickyBroadcast()
、sendOrderBroadcast()
Method sends a broadcast message if theBroadcastReceiver
Also “interested” in the news,BroadcastReceiver
的onReceive ( Context context, Intetn intent )
The method will be fired. - Use steps:
- For instance call LocalBroadcastManager. GetInstance ()
- Call the registerReceiver() method to register the broadcast
- Call the sendBroadcast() method to send a broadcast
- Call the unregisterReceiver() method to cancel registration
1.7.1 Precautions:
- Local broadcasts cannot be accepted through static registration and are more efficient than system global broadcasts.
- Start on the air
Activity
Is requiredIntent
joinFLAG_ACTIVITY_NEW_TASK
Flag, otherwise an error is reported because a stack is required to hold the newly openedActivity
。 - Pop up on broadcast
Alertdialog
“, you need to set the dialog box type toTYPE_SYSTEM_ALERT
Otherwise, it cannot be ejected. - Don’t in
onReceiver()
Method to add too much logic or perform any time-consuming operations, since threads are not allowed to open in the broadcast receiver, whenonReceiver()
When a method runs for a long time without ending, the program reports an error.
1.8 Sticky Broadcast Sticky Broadcast
- If the sender sends a broadcast and the Receiver registers his or her own Receiver after the broadcast is sent, then the Receiver cannot receive the broadcast
- To do this
Android
The introduction of theStickyBroadcast
, the broadcast just sent will be saved after the broadcast is sent (Intent
), so that when the recipient is finished registeringReceiver
Then you can continue to use the broadcast. - If multiple copies of the same are sent before the recipient’s registration is completed
Action
You will only receive one sticky broadcast after registeringAction
And the message is the last broadcast. - A change in the network state of the system sends a broadcast that is called a sticky broadcast.
- Viscous broadcast passage
Context
的sendStickyBroadcast ( Intent )
Interface send, need to add permission USES - the permission of the android: name = "android permission. BROADCAST_STICKY"
- Also through
Context
的removeStickyBroadcast ( Intent intent )
Interface removes cached sticky broadcasts
1.9 LocalBroadcastManager,
1.9.1 features:
- Broadcasts sent from it will only spread within your APP, so you don’t have to worry about leaking private data;
- other
APP
Can’t do anything to youAPP
Send this broadcast, because your APP can’t possibly receive this broadcast from a non-app, so you don’t have to worry about security vulnerabilities to exploit it; - More efficient than the global broadcast of the system.
1.9.2 Source code analysis:
LocalBroadcastManager
Internal collaboration mainly depends on these twoMap
Collection:MReceivers
和MActions
And, of course, a List collectionMPendingBroadcasts
, this is mainly to store the broadcast object to be received.LocalBroadcastManager
The reason for the efficiency is mainly because it is internally throughHandler
Realized, itssendBroadcast()
The meaning of the method is not the same as what we usually use, itssendBroadcast()
And the way to do that is byhandler
Send aMessage
The implementation;- Now that it’s inside is through
Handler
To achieve broadcast transmission, then compared to the system broadcast throughBinder
Achieving that is certainly more efficient while usingHandler
Other applications cannot send this broadcast to our application, and the broadcast sent within our application will not leave our application;
1.9.3 BroadcastReceiver Security Issues
BroadcastReceiver
It was designed from a global perspective to facilitate communication between applications and systems, between applications, and within applications, so for a single applicationBroadcastReceiver
There are security issues (malicious scripts constantly sending the broadcasts you receive). To solve this problemLocalBroadcastManager
And that’s what happened.LocalBroadcastManager
是Android Support
Packages provide a tool for sending between different components within the same applicationBroadcast
.LocalBroadcastManager
Also known as local notification manager, the benefits of this kind of notification is high security, high efficiency, suitable for local communication, can be used insteadHandler
updateUI
1.9.4 Broadcast security
Android
Broadcasts in the system can communicate directly across processes, which may cause the following two problems:
- other
APP
Can receive the currentAPP
Broadcast sent, resulting in data leakage. - other
APP
You can call the currentAPP
Broadcast a message that led toAPP
Illegally controlled.
- Send broadcast
- When sending a broadcast, add the corresponding
permission
Is used for permission verification. - in
The Android 4.0
Can be used when sending broadcast in the above systemsetPackage()
Method to set the name of the packet to receive the broadcast. - Use local broadcast.
- Accept radio
- When registering a broadcast receiver, add the corresponding
permission
Is used for permission verification. - Set when registering a broadcast receiver
android:exported
Is false.
- Use local broadcast
- When sending a broadcast, if added
permission
- The one on the radio
APP
You must apply for permission to receive the broadcast, and vice versa.
1.9.5 Benefits of Using BroadcastReceiver
- As broadcast data spreads within the application, you don’t have to worry about privacy data leakage.
- There is no need to worry about other applications forgery broadcast, causing security risks.
- It is more efficient than sending a global broadcast within the system.
1.10 How to let my broadcast only be received by the specified app?
- Sending a broadcast
app
End, custom defined permissions, then want to receive in additionapp
The end must declare permissions to receive.
- Permission: The protection level is normal.
- User permissions
<permission android:name="broad.ok.receiver" android:protectionLevel="normal"/>
<uses-permission android:name="broad.ok.receiver" />
Copy the code
- Send a broadcast with a permission string
public void click(View view) { Intent intent = new Intent(); Intent. PutExtra ("info", "message content "); intent.setAction("myBroadcast.action.call"); sendBroadcast(intent, "broad.ok.receiver"); //sendOrderedBroadcast(intent,"broad.ok.receiver"); }Copy the code
- Other app recipients who want to access broadcasts must declare permissions in the manifest file
<uses-permission android:name="broad.ok.receiver"/>
Copy the code
1.11 Does broadcast Priority Take effect for Out-of-order Broadcasts?
- Priority also applies to disorder.
1.12 Who has the highest Priority for dynamically registered broadcasts?
- Whoever registers first will be taller
1.13 How do I determine whether the Current BrodcastReceiver receives orderly or out-of-order broadcasts?
- in
onReceiver
Method, which calls the return value of the judgment method directly
Public void onReceive(Context Context, Intent Intent) {log. d("MyBroadCastReceiver", "emsp; + intent.getStringExtra("info") + ""); boolean isOrderBroadcast = isOrderedBroadcast(); }Copy the code
1.14 BroadcastReceiver Cannot Perform time-consuming operations
- On the one hand,
BroadcastReceiver
Usually in the main thread.- Time-consuming operations cause
ANR
- On the other hand
BroadcastReceiver
The startup time is short.- If only one exists in a process
BroadcastReceiver
Components. It also opens child threads to perform time-consuming tasks. - The system considers this process to be an empty process with the lowest priority. It’s easy to kill.
conclusion
-
This article provides a thorough summary of BroadcastReceiver and ContentProvider knowledge. If you have any additional knowledge, please feel free to point it out in the comments section.
-
I hope you found this reading interesting.