Android broadcast mechanism anatomy "Android radio series One"

Source: Internet
Author: User

Broadcast is one of the four major Android components, so the importance of broadcasting is also obvious, recently need to do a function, need to understand the mechanism of broadcasting, so I put the idea. Usually when we write code, the broadcast is only used to inform the mechanism, not for communication mechanism, communication mechanism or to use binder mechanism to achieve. But now most third-party apps on the market are abusing the radio, using broadcasts to monitor events for self-booting or background booting. This is a misunderstanding of Google's meaning. Originally very good components, was abused, causing users to always feel that the mobile phone program is not control, always secretly start the background. Small white users even more do not understand. Okay, now we're on.
Android broadcasts are divided into three types by sending:

    • Shuffle broadcast
    • Orderly broadcast: Orderedbroadcast
    • Adhesion broadcast: Stickybroadcast

There are two types of broadcasting in the form of registration:

    • Static broadcast
    • Dynamic broadcast

      Excerpt from Lao Luo's article "Broadcast mechanism is an event-driven model based on message publishing and subscription, that is, the broadcast sender is responsible for publishing the message, and the broadcast receiver needs to subscribe to the message before it can receive the message." In the broadcasting mechanism, the broadcast sender does not need to know the existence of the broadcast receiver beforehand, so it can greatly reduce the coupling between the broadcast sender and the broadcast receiver, and improve the expansibility and maintainability of the system. ”
      The true mechanism of broadcasting is in two cases, the mechanism of registering broadcasting, and the mechanism of receiving broadcasting, let us first talk about the process of registering broadcasting.
      The process of registering a broadcast: Two kinds of dynamic registration and static registration;
      (1) First, dynamic registration of the broadcast
      STEP1: Description: Receiverdispatcher is frameworks/base/core/java/android/app/ Loadedapk.java's inner class, which is the component that holds the broadcast recipient (activity or service), is responsible for associating the registered broadcast receiver with the component that registered it.

    Static Final  class receiverdispatcher {    Final Static  class innerreceiver extends iintentreceiver. Stub {. . . . . .    . . . . . . }//Please note this field! It is the RD that is spread out.     FinalIintentreceiver.stub Miintentreceiver;FinalBroadcastreceiver Mreceiver;FinalContext Mcontext;FinalHandler Mactivitythread;FinalInstrumentation minstrumentation;Final Booleanmregistered;FinalIntentreceiverleaked mlocation; RuntimeException munregisterlocation;BooleanMforgotten; . . . . . .

STEP2: All right, let's talk about what you need to know. Registerreceiver (), is registered through the context, the call process is finally called to the Contextimpl object,

@OverridepublicregisterReceiver(BroadcastReceiver receiver, IntentFilter filter)  {        returnnullnull);}@OverridepublicregisterReceiver(BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler) {       return registerReceiverInternal(receiver, filter, broadcastPermission,  scheduler, getOuterContext());}

STEP3: Let's take a look at the Registerreceiverinternal () method:

Private Intent registerreceiverinternal (broadcastreceiver receiver, Intentfilter filter, String broadcastperm Ission, Handler Scheduler, Context context) {Iintentreceiver rd = null;if(receiver! = NULL) {if(Mpackageinfo! = NULL && context! = NULL) {if(Scheduler = = NULL)            {scheduler = Mmainthread.gethandler (); }//Find and context corresponding "sub hash table" In the receiverdispatcher,//if not found, re-new rd = Mpackageinfo.getreceiverdispatche R (receiver, context, scheduler, Mmainthread.getinstrumentation (), True)        ; }Else{if(Scheduler = = NULL)            {scheduler = Mmainthread.gethandler (); } rd = new Loadedapk.receiverdispatcher (...,...);    }        . . . . . . }Try{returnActivitymanagernative.getdefault (). Registerreceiver (Mmainthread.getapplicationthread (), MBasePackageName,    Rd, filter, broadcastpermission); } catch (RemoteException e) {returnNull }}

STEP4: Attention to that Rd object (Iintentreceiver Rd), first call member function of member variable Mpackageinfo (is an object of loadedapk) Getreceiverdispatcher () The broadcast receiver receiver is encapsulated into a local object rd that implements the binder for the Iintentreceiver interface, and finally the object is sent to Acitivitymanagerservice.
Then take a look at the Getreceiverdispatcher () method:

 PublicIintentreceiver Getreceiverdispatcher (Broadcastreceiver R, Context context, Handler Handler, Instrum Entation Instrumentation, Boolean registered) {synchronized (mreceivers) {loadedapk.Receiverdispatcher Rd= NULL;//Registered broadcast receiver is associated with the component that registered itArraymap<Broadcastreceiver, loadedapk.Receiverdispatcher> Map = NULL;//already registered            if(registered) {Map =Mreceivers.Get (context);if(Map != NULL) {Rd= Map.Get (R); }            }//Do not associate receivers and components together, i.e. not registered            if(Rd== NULL) {Rd= NewReceiverdispatcher (r, context, handler, instrumentation, registered);if(registered) {if(Map == NULL) {Map = NewArraymap<Broadcastreceiver, loadedapk.Receiverdispatcher>(); Mreceivers.Put (context,Map); }Map.Put (R, RD); }            }Else{Rd.Validate (context, handler); } Rd.Mforgotten= false;//To obtain a local object that implements the binder for the Iintentreceiver interface            returnRd.Getiintentreceiver (); }}iintentreceiver Getiintentreceiver () {returnMiintentreceiver; }

STEP5: And then we'll see where the miintentreceiver is assigned,

Static Final  class receiverdispatcher {        Final Static  class innerreceiver extends iintentreceiver. Stub {            FinalWeakreference<loadedapk.receiverdispatcher> Mdispatcher;FinalLoadedapk.receiverdispatcher Mstrongref; }receiverdispatcher (Broadcastreceiver Receiver, context context, Handler Activitythread, instrumentation in Strumentation,BooleanRegistered) {if(Activitythread = =NULL) {Throw NewNullPointerException ("Handler must not being null"); }//A local object that points to a binder that implements the Iintentreceiver interfaceMiintentreceiver =NewInnerreceiver ( This,!registered);            Mreceiver = receiver;            Mcontext = context;            Mactivitythread = Activitythread;            Minstrumentation = instrumentation;            mregistered = registered; Mlocation =NewIntentreceiverleaked (NULL);        Mlocation.fillinstacktrace (); }}

STEP6: Note: This Innerreceiver object has a weak reference mdispatcher of type Receiverdispatcher, which points to an external Receiverdispatcher object.
Then it was registered in AMS. The code is as follows:

 PublicIntentRegisterreceiver(Iapplicationthread caller, string callerpackage, Iintentreceiver receiver, Intentfilter filter, String Permiss IonintUserId) {Enforcenotisolatedcaller ("Registerreceiver");intCallinguid;intCallingpid; Synchronized This) {Processrecord Callerapp =NULL;if(Caller! =NULL) {//Get caller's ProcessrecordCallerapp = getrecordforapplocked (caller);if(Callerapp = =NULL) {Throw NewSecurityException ("Unable to find app for caller"+ caller +"(pid=" )+ binder.getcallingpid () +") When registering receiver"+ receiver); }if(CallerApp.info.uid! = Process.system_uid &&!callerapp.pkglist.containskey (callerpackage) &&!"Android". Equals (Callerpackage)) {Throw NewSecurityException ("Given Caller Package"+ Callerpackage +"is not running in process"+ Callerapp);                } callinguid = CallerApp.info.uid;            Callingpid = Callerapp.pid; }Else{callerpackage =NULL;                Callinguid = Binder.getcallinguid ();            Callingpid = Binder.getcallingpid (); } userId = This. Handleincominguser (Callingpid, Callinguid, UserId,true, Allow_full_only,"Registerreceiver", callerpackage); List Allsticky =NULL;//Look for any matching sticky broadcasts ...Iterator actions = Filter.actionsiterator ();if(Actions! =NULL) { while(Actions.hasnext ())                    {String action = (string) actions.next ();                    Allsticky = getstickieslocked (action, filter, Allsticky, Userhandle.user_all);                 Allsticky = getstickieslocked (action, filter, Allsticky, Userhandle.getuserid (Callinguid)); }            }Else{Allsticky = getstickieslocked (NULL, filter, Allsticky, Userhandle.user_all); Allsticky = getstickieslocked (NULL, filter, Allsticky, Userhandle.getuserid (Callinguid)); }// The first sticky in the list was returned directly back to            //The client.//determines if sticky broadcasts are nullIntent sticky = allsticky! =NULL? (Intent) Allsticky.Get(0) :NULL;if(Debug_broadcast) SLOG.V (TAG,"Register receiver"+ Filter +": "+ sticky);if(Receiver = =NULL) {returnSticky } receiverlist RL//This piece of code is very valuable to look at. = (receiverlist) mregisteredreceivers.Get(Receiver.asbinder ());if(RL = =NULL) {RL =NewReceiverlist ( This, Callerapp, Callingpid, Callinguid, userId, receiver);if(Rl.app! =NULL) {Rl.app.receivers.add (RL); }Else{Try{Receiver.asbinder (). Linktodeath (RL,0); }Catch(RemoteException e) {returnSticky } Rl.linkedtodeath =true;            } mregisteredreceivers.put (Receiver.asbinder (), RL); }Else if(Rl.uid! = callinguid) {Throw NewIllegalArgumentException ("Receiver requested to register for UID"+ Callinguid +"was previously registered for UID"+ Rl.uid); }Else if(Rl.pid! = callingpid) {Throw NewIllegalArgumentException ("Receiver requested to register for PID"+ Callingpid +"was previously registered for PID"+ rl.pid); }Else if(Rl.userid! = userId) {Throw NewIllegalArgumentException ("Receiver requested to register for user"+ UserId +"was previously registered for user"+ Rl.userid); } broadcastfilter bf =NewBroadcastfilter (filter, RL, Callerpackage, permission, Callinguid, userId); Rl.add (BF);if(!bf.debugcheck ()) {SLOG.W (TAG,"==> for Dynamic broadast"); } mreceiverresolver.addfilter (BF);//Enqueue broadcasts for all existing stickies that match            //This filter.            if(Allsticky! =NULL) {ArrayList receivers =NewArrayList (); Receivers.add (BF);intN = Allsticky.size (); for(intI=0; i<n; i++) {Intent Intent = (Intent) allsticky.Get(i);                    Broadcastqueue queue = broadcastqueueforintent (intent); Broadcastrecord r =NewBroadcastrecord (queue, intent,NULL,NULL, -1, -1,NULL,NULL, Appopsmanager.op_none, receivers,NULL,0,NULL,NULL,false,true,true, -1);                    Queue.enqueueparallelbroadcastlocked (R);                Queue.schedulebroadcastslocked (); }            }returnSticky }    }

All right, let's get here today, follow up and finish ...

Android broadcast mechanism anatomy "Android radio series One"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.