-
- Introduction to broadcasting mechanism
- Broadcast classification
- Standard broadcast
- Orderly broadcast
- Receive system broadcast
- Dynamic Registration monitoring Network changes
- Static registration for boot start
- Note Time-consuming operations
- Send Custom Broadcasts
- Send an ordered broadcast
- Send ordered broadcast steps
- Priority level
- Use local broadcast
- Cause of Occurrence
- Local broadcast use
- Advantages
- Broadcast priority
- Basic principles
- Ordered broadcast
- Non-ordered broadcast
- Only dynamically accept broadcast source code analysis
- Objective
- Reference httpblogcsdnnetgemmemarticledetails8859493
- Analysis of broadcast registration process
- Process for statically registering Receiver
- The process of registering Receiver dynamically
- Analysis of broadcast sending process
- Analysis
- Summarize
- Reference httpwww2ctocomkf201408325326html
Introduction to broadcasting mechanism
Broadcasting is a way of communicating across processes (e.g., receiving system broadcasts).
Android broadcasts are a one-way notification of whether the recipient is receiving processing or how to handle the broadcast. Android uses Braodcastreceiver to listen to broadcasts from the system, and different braodcastreceiver distinguish the type of listening broadcast by setting different fliter. Some broadcasts require the appropriate permission to listen.
Broadcast classification
- Standard broadcast (normal broadcast)
- Orderly broadcast (Ordered broadcast)
Standard broadcast
Standard broadcast: A fully asynchronous broadcast, after the broadcast occurs, all broadcasts receive broadcast messages at the same time, without any sequencing, high efficiency, but cannot be truncated.
Orderly broadcast
Orderly broadcast: Synchronous execution of the broadcast, after the broadcast, only one broadcast receiver can receive this broadcast message, when the logic in the broadcast receiver is completed, the broadcast will continue to pass, the broadcast receiver has a sequence, high priority received first, and can be truncated, the latter cannot be received.
Receive system broadcast
Braodcastreceiver must be registered to have the ability to listen, there are two ways to register:
Broadcast Registration method: Registered in the code, also known as dynamic registration. and register in the androidmanifest.xml manifest file.
Dynamic Registration monitoring Network changes
(1) Create a broadcast receiver
Create a new inner class, let him inherit Broadcastreceiver, and override the OnReceive () method of the parent class.
(2) The code registers the broadcast.
(3) Code example
Public class mainactivity extends Activity {Intentfilter Intentfilter; Mybroadcastreceiver Myreceiver; @Overrideprotected voidOnCreate (Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main); Intentfilter =NewIntentfilter (); Intentfilter.addaction ("Android.net.conn.CONNECTIVITY_CHANGE"); Myreceiver =NewMybroadcastreceiver ();//Registered broadcastRegisterreceiver (Myreceiver, Intentfilter); } @Overrideprotected voidOnDestroy () {Super. OnDestroy (); Unregisterreceiver (Myreceiver); } class mybroadcastreceiver extends broadcastreceiver{@Override Public voidOnReceive (context context, Intent Intent) {Connectivitymanager cm = (Connectivitymanager) getsystemservice (Cont Ext. Connectivity_service); Networkinfo networkinfo = Cm.getactivenetworkinfo (); Toast.maketext (mainactivity. This,"I am Change"+ networkinfo.getstate (), Toast.length_long). Show (); } }}
Add permissions to get network status.
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
Static registration for boot start
(1) The disadvantage of dynamic registration: The broadcast must be received when the program is opened.
(2) Therefore, static registration solves this problem.
Static Registration steps:
- Create a new class that inherits Broadcastreceiver, implements Onreceiver (), and is no longer an inner class.
- Register in Androidmanifest.xml, at this time is as four components, with tags, plus and so on, pay attention to also need to add relevant permissions.
Bootcompletereceiver. java
publicclass BootCompleteReceiver extends BroadcastReceiver { @Override publicvoidonReceive(Context context, Intent intent) { "Boot Complete", Toast.LENGTH_LONG).show(); }}
权限 <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />注册<receiver android:name=".BootCompleteReceiver" > <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </receiver>
Note Time-consuming operations
Do not add too much logic or take time-consuming actions in OnReceive (). Because the broadcast receiver does not allow the thread to be opened, the program will give an error when onreceive () runs for a longer period of time without ending. 8s or so, more than the need to consider transfer processing. (for example, start a service here and operate in the service?) )。
Send Custom Broadcasts
- Register and the corresponding action in the manifest file.
- In the place of Use sendbroadcast (intent)
The intent constructor passes in the action as a parameter (String). At the same time, using intent can also carry data.
new Intent( "com.example.broadcasttest.MY_BROADCAS");sendBroadcast(intent);
public class mybroadcastreceiver extends broadcastreceiver { @Override public void onreceive (context context, Intent Intent) {Toast.maketex T (context, "received in Mybroadcastreceive" , Toast.length_short). Show (); }}
//这里的action是自定义的,不是android自带<receiver android:name=".MyBroadcastReceiver"> <intent-filter> <action android:name="com.example.broadcasttest.MY_BROADCAST"/> </intent-filter> </receiver>
Note: The broadcast before this is a standard broadcast
Send an ordered broadcast to send an ordered broadcast step
- Sendorderbroadcast (Intent, NULL)
- When registering, set the priority. or set by calling the SetPriority () of the Intentfilter object.
- Truncation: Abortbroadcast () is called in the receiver with high priority, and subsequent receivers are not received.
Priority level
- Range: -1000~1000, but the actual maximum value is 2147483647 of the maximum value that can be reached for int.
Reason for using local broadcast
The broadcasts that were sent and received in the front are all system global broadcasts, that is, broadcasts that are sent can be received by any other program, and we can also receive broadcasts from other programs. This leads to security issues (such as critical data or spam broadcasts).
Therefore, the introduction of local broadcast mechanism can only be passed within the application, and the broadcast receivers in the local broadcast mechanism can only receive broadcasts from this application.
Local broadcast use
- Localbroadcastmanager to manage the broadcast.
- Localbroadcastmanager Localbroadcastmanager;
Localbroadcastmanager = Localbroadcastmanager.getinstance (this);
- Localbroadcastmanager.sendbroadcast (Intent);
- Register local broadcast Listener localbroadcastmanager.registerreceiver (Localreceiver, Intentfilter);
- Localbroadcastmanager.unregisterreceiver (Localreceiver);
Code:
Public class mainactivity extends Activity { PrivateIntentfilter Intentfilter;PrivateLocalreceiver Localreceiver;PrivateLocalbroadcastmanager Localbroadcastmanager;@Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main); Localbroadcastmanager = Localbroadcastmanager.getinstance ( This); Button button = (button) Findviewbyid (R.id.button); Button.setonclicklistener (NewOnclicklistener () {@Override Public void OnClick(View v) {Intent Intent =NewIntent ("Com.example.broadcasttest.LOCAL_BROADCAST"); Localbroadcastmanager.sendbroadcast (Intent); } }); Intentfilter =NewIntentfilter (); Intentfilter.addaction ("Com.example.broadcasttest.LOCAL_BROADCAST"); Localreceiver =NewLocalreceiver (); Localbroadcastmanager.registerreceiver (Localreceiver, Intentfilter); }@Override protected void OnDestroy() {Super. OnDestroy (); Localbroadcastmanager.unregisterreceiver (Localreceiver); } class Localreceiver extends Broadcastreceiver {@Override Public void OnReceive(context context, Intent Intent) {Toast.maketext (context,"received local broadcast", Toast.length_short). Show (); } }}
Advantages
A local broadcast cannot be received by a static registration method. In fact, it's completely
It is understandable, because static registration is primarily to allow the program to receive broadcasts without booting, and to send local
When broadcasting, our program must have been started, so there is absolutely no need to use the static registration function.
Finally, let's take a look at some of the advantages of using local broadcast.
1. You can clearly know that the broadcast being sent will not leave our program, so there is no need to worry about confidential data leakage
The problem of leakage.
2. Other programs cannot send broadcasts to the inside of our program, so there is no need to worry about security breaches
Patient
3. Sending a local broadcast is more efficient than sending a system global broadcast.
Broadcast Priority Fundamentals
The order in which the receivers receiving an unordered broadcast receive broadcasts is ordered (determined by priority order)
Receivers that receive out-of-order broadcasts can also set the priority
Dynamic registration broadcast priority higher than static registered broadcast
A dynamic receiver of equal priority, first registered first received
Static receivers of equal priority, the order in which the broadcasts are received is consistent with the order of string[] Java.io.File.list ()
Ps: One thing to note here is that the order of reception of static receivers of equal priority is uncertain, because the order of file.list () is uncertain, and if you need to see the order in which a receiver is received, it is best to experiment with a large number of apk names.
Ordered broadcast
Assuming 5 receivers like the next priority
1. Dynamic A (priority =1)
2. Dynamic B (priority =2)
3. Dynamic C (priority =2)
4. Static D (priority =1)
5. Static E (priority =2)
and B is registered prior to C
Then the actual receive order should be
B C E A D
That is, if the static receiver takes precedence over the priority of the dynamic receiver, then the static receiver receives the broadcast first (such as receiving SMS broadcasts)
Non-ordered broadcast
Dynamic receiver high-priority > Dynamic receiver Low priority > static receiver High priority > static receiver Low-priority
Only dynamically accept broadcast source code analysis
Some broadcasts, we cannot receive with static receivers, such as action_screen_on, when the screen is lit, the system sends this broadcast.
void com .android .server .initinthread () Java code void Initinthread () {?? Mscreenonintent = new Intent (intent _screen_on) ; Mscreenonintent.addflags (Intent _receiver_registered_only) ; Mscreenoffintent = new Intent (intent _screen_off) ; Mscreenoffintent.addflags (Intent _receiver_registered_only) ; ??}
Intent.flag_receiver_registered_only is set in Intent, so if you want to receive it, you must dynamically register the broadcast sink Action_screen_off as well. Similar also: Action_time_tick, action_battery_changed.
Objective
Many virus programs in order to ensure that they are terminated to run again, will be in the XML to register some system broadcast, in an attempt to use these system high-frequency broadcast to achieve self-booting.
For example, in older versions of Android, the virus program can start its own service background by listening to Time_tick, doing some covert work, and even if it is killed, it can be restarted very quickly.
And once these systems broadcast with FLAG flag_receiver_registered_only, these virus programs are out of control. Google's changes have undoubtedly enhanced the security of Android.
Reference: http://blog.csdn.net/gemmem/article/details/8859493 Broadcast registration process analyzing the process of statically registering Receiver
Static receiver registration is initiated by the Packagemanagerservice when the initial PMS at boot time will be on the system some directory scanning, parsing apk file. Static broadcast receivers are handled by the PMS when doing this.
The PMS parses the APK's manifest file, finds the receiver registered here, and loads it into memory.
The order in which the PMS initializes the scanned directories:
System/framework
System/app
Vendor/app
Data/appd
Rm/app-private
We see how the PMS parses the manifest at initialization and stores the element in memory where receiver is stored in the member variable receivers of owner, and the type of owner is
Android.content.pm.PackageParser.Package This means that Scanpackageli returns the package object that already contains the manifest information.
The process of registering Receiver dynamically
Dynamic registration is eventually called to the Registerreceiver function in AMS, and eventually all dynamically registered receiver are saved to the member variable mreceiverresolver of AMS. Static broadcast and dynamic broadcast how to register, we have all finished analysis. Static broadcast is packagemanagerservice responsible for saving to its member variable mreceivers, which is activitymanagerservice responsible for saving to its member variable mreceiverresolver.
Analysis and analysis of broadcast transmission process
The implementation of the Sendbroadcast function in the Context is in Contextimpl, and there are six functions associated with sending the broadcast: void Android. App. Contextimpl. Sendbroadcast(Intent Intent) void Android. App. Contextimpl. Sendbroadcast(Intent Intent, String receiverpermission) void Android. App. Contextimpl. Sendorderedbroadcast(Intent Intent, String receiverpermission) void Android. App. Contextimpl. Sendorderedbroadcast(Intent Intent, String receiverpermission,broadcastreceiver resultreceiver, Handler Scheduler, int initialcode, string Initialdata,bundle initialextras) void Android. App. Contextimpl. Sendstickybroadcast(Intent Intent) void Android. App. Contextimpl. Sendstickyorderedbroadcast(Intent Intent, Broadcastreceiverresultreceiver, Handler Scheduler, int initialcode, String initialdata, Bundleinitialextras)
Can be divided into 3 groups: 1 General Broadcasting, 2 Ordered broadcast, 3 Sticky broadcast. Either way, the final will be by the AMS, if the non-ordered broadcast, then mparallelbroadcasts will store all dynamic receivers, and then merge, mparallelbroadcasts is set to NULL, so will not be merged into Receivers, if it is ordered broadcast, then Mparallelbroadcasts will be merged into receivers, then, regardless of what kind of broadcast, finally call schedulebroadcastslocked continue processing, eventually to The Processnextbroadcast function. The broadcast is ordered, which is set by the Boolean variable ordered.
Summarize
The sending process is divided into two types (schedulebroadcastslocked), ordered broadcast and non-ordered broadcast, and non-ordered broadcast. The receiver is processed first, then the static receiver ordered broadcast simultaneously processes both the dynamic receiver and the static receiver, first merging the dynamic receiver with the static receiver, maintaining the same order of precedence, high priority in front, otherwise the order is unchanged. The static receiver and the dynamic receiver have the same priority, the dynamic receiver is in front.
Reference: http://www.2cto.com/kf/201408/325326.html
Broadcast--broadcast