Android Source Series < 11 > from the perspective of the source of deep understanding Accessibilityservice, to create their own app small plug (bottom)

Source: Internet
Author: User

Reprint Please specify source: http://blog.csdn.net/llew2011/article/details/52843637

In the previous article Android source code series < 10 > from the point of view of the source of deep understanding accessibilityservice, build their own app small plug (on) We explained through the Accessibilityservice implementation of the automatic installation APK small plug operation process, if you have not read the previous article click here. In this article I will lead the small partner from the point of view of the source to learn more about the principle of accessibilityservie technology, I hope this article can give small partners a little help, if you are familiar with this piece, congratulations you can pass this article (*^__^*) ...

In the previous article we mentioned that Accessibilityservice is a subclass of service whose life cycle is maintained and managed by the system, and the official annotations of this class are as follows:

/** * Accessibility Services is intended to assist users with disabilities in using * Android devices and apps. They run in the background and receive callbacks by the system * When {@link accessibilityevent}s is fired. Such events denote some state transition * in the user interface, for example, the focus have changed, a button has been CL icked, * etc. Such A service can optionally request the capability for querying the content * of the active window. Development of an accessibility service requires extending this * class and implementing its abstract methods. * * * Through official annotations We know that the life cycle of Accessibilityservice is managed by the system, and the service is turned on on the Android device's settings page, Shutting down the service is also done either by closing the settings page or by calling Accessibilityservice's Disableself () method. Because Accessibilityservice is a subclass of the service, Accessibilityservice has all the accessible methods of the service, After the overall reading browsing Accessibilityservice source found that Accessibilityservice only rewrite the Onbind () method, the code is as follows:
@Overridepublic final IBinder onbind (Intent Intent) {    return new Iaccessibilityserviceclientwrapper (this, Getmainlooper (), new callbacks () {/** omitted */});
The Onbind () method returns a Iaccessibilityserviceclientwrapper (hereinafter referred to as a IASCW) instance object that requires three parameters to be passed when the instance object is initialized: Context,looper and callbacks , then why do you want these three parameters, what are the effects of these three parameters? IASCW is He Shan again? At present we can only guess IASCW is definitely implemented or indirectly implemented the IBinder interface, and then look down at the source of the class, as follows:
/** * Implements The internal {@link Iaccessibilityserviceclient} interface to convert * Incoming calls to it back to calls on an {@link A Ccessibilityservice}. * * @hide */public static class Iaccessibilityserviceclientwrapper extends Iaccessibilityserviceclient.stub impleme NTS Handlercaller.callback {//...    Omit ... private final handlercaller Mcaller;    Private final callbacks Mcallback; Public Iaccessibilityserviceclientwrapper (context context, Looper Looper, callbacks callback) {Mcallback = Callbac        K    Mcaller = new Handlercaller (context, Looper, this, true/*asynchandler*/); }    // ...... Omit ... @Override public void executemessage (Message message) {//... Omit ...}} 
According to the source we found that IASCW inherited the iaccessibilityserviceclient.stub and realized the Handlercaller.callback interface, see iaccessibilityserviceclient.stub after the small partners if the Communication between processes should be understood Accessibilityservice is the use of interprocess communication mechanism, and iaccessibilityserviceclient defined Aidl source code is as follows:
OneWay interface Iaccessibilityserviceclient {    void init (in iaccessibilityserviceconnection connection, int ConnectionID, IBinder windowtoken);    void Onaccessibilityevent (in accessibilityevent event);    void Oninterrupt ();    void ongesture (int gesture);    void Clearaccessibilitycache ();    void Onkeyevent (in keyevent event, int sequence);    void Onmagnificationchanged (in region, float scale, float centerx, float centery);    void onsoftkeyboardshowmodechanged (int showmode);    void Onperformgestureresult (int sequence, Boolean completedsuccessfully);}
        After the Iaccessibilityserviceclient.aidl file is saved, the compiler automatically generates the corresponding Java class in the corresponding package directory, and an internal static abstract class stub is automatically generated in the class, and the stub class inherits Android.os.Binder (Binder implements the IBinder interface) and implements the Iaccessibilityserviceclient interface, which generates an internal static class proxy inside the stub. The class also implements the Iaccessibilityserviceclient interface, so the final aidl execution result is the result of the proxy agent execution in the stub. A Handlercaller object was initialized in IASCW's construction method, what is Handlercaller for? We enter the source code to look at:
public    Class Handlercaller {final Looper mmainlooper;    Final Handler MH;    Final Callback Mcallback; Class MyHandler extends Handler {//...        Omit ... @Override public void Handlemessage (Message msg) {mcallback.executemessage (msg);    }} public interface Callback {public void ExecuteMessage (Message msg); } public Handlercaller (context context, Looper Looper, Callback Callback, Boolean asynchandler) {mmainlooper = Looper! = null?        Looper:context.getMainLooper ();        MH = new MyHandler (Mmainlooper, Asynchandler);    Mcallback = callback; }//The following omits a method of the same name for the defined handler, in which the corresponding method of handler is called in the method} 
By reading the source code of Handlercaller we can conclude that the main function of Handlercaller is to hold the handler instance object of the context thread MH, and then continue to the context of the thread of the message queue to send messages, The Mcallback ExecuteMessage () method is then called in the MH callback method Handlemessage (), and the Mcallback instance object is IASCW, so the IASCW executemessage () is finally called. Method. The sum up is to let IASCW's ExecuteMessage () method execute in the thread where the context is located (in fact, it is executed in the main path). The ExecuteMessage () method code is as follows:
@Overridepublic void executemessage (Message message) {    switch (message.what) {case                do_on_interrupt: {            Mcallback.oninterrupt ();        } return;                // ...... Omit ...    }
The ExecuteMessage () method invokes the corresponding method through the message type, such as Oninterrupt () method called Mcallback when the message type is Do_on_interrupt, Mcallback () in Oninterrupt Method is called the Accessibilityservice Oninterrupt () method, the source code is as follows:
@Overridepublic final IBinder onbind (Intent Intent) {    return new Iaccessibilityserviceclientwrapper (this, Getmainlooper (), new callbacks () {        @Override public        void Oninterrupt () {            AccessibilityService.this.onInterrupt ();        }        // ...... Omit ...    });

Here we are probably clear about the system to feed the event message to Accessibilityservice's approximate process, The main process is that the system passes the event message to Accessibilityservice and calls Accessibilityservice's Onaccessibilityevent () method after the interprocess communication mechanism. In this method we can do different business operations based on the event type.

Knowing the Accessibilityservice response process, there may be a small partner asking how the Android system knows when to send an event message to Accessibilityservice. Is the Android system constantly monitoring every application? With this question we continue to look at the source code, the answer is in the source code.

Small partners should be familiar with the view architecture and event delivery in the Android system, please check it yourself (I am already preparing this knowledge point, I can publish it soon), view is the smallest display unit in the Android UI, See the view source of the child boots should remember that the view implementation of three interfaces, one of the interface is Accessibilityeventsource, the structure is defined as follows;

Public interface Accessibilityeventsource {    /**     * Send secondary events, verify parameters */     public    Void sendaccessibilityevent (int eventtype);    /**     * Send auxiliary events, do not validate parameters     *    /public void sendaccessibilityeventunchecked (Accessibilityevent event);}
The Accessibilityeventsource interface indicates that a related auxiliary event is sent to the system, and since the view implements this interface, which means that both the view and its subclasses have the ability to send auxiliary events to the system, we first remember this conclusion and then look down at the code.
In the view system when we click on a button, if the button set the Onclicklistener event listener, then when the button is clicked to call back the listener's onclick () method, when the onclick () function is called? We find the answer from the source code as follows:
public boolean ontouchevent (Motionevent event) {//...            Omit ... if (((viewflags & clickable) = = Clickable | |            (ViewFlags & long_clickable) = = long_clickable) | | (ViewFlags & context_clickable) = = context_clickable) {switch (action) {case MOTIONEVENT.ACTION_UP                : Boolean prepressed = (Mprivateflags & pflag_prepressed)! = 0; if ((Mprivateflags & pflag_pressed)! = 0 | | prepressed) {//... Omit ... if (!mhasperformedlongpress &&!mignorenextupevent) {if (!FOC  Ustaken) {//focus here, finally callback the PerformClick () method if (Mperformclick = = null)                            {Mperformclick = new PerformClick ();                            } if (!post (Mperformclick)) {PerformClick ();               }         }                    }                }            }            // ......        Omit ...}    return true; } return false;}
By finding the source code, we found that in the Action_up branch of the View Ontouchevent (), the PerformClick () method was finally called after layers of judgment, according to which the method name can be guessed to execute the click Method, we enter the PerformClick () method take a look, the source code is as follows:
public boolean PerformClick () {    final boolean result;    Final Listenerinfo li = mlistenerinfo;    if (Li! = null && Li.monclicklistener! = null) {        playsoundeffect (soundeffectconstants.click);        Li.mOnClickListener.onClick (this);        result = true;    } else {        result = false;    }    Notice here that a accessibilityevent event    sendaccessibilityevent (accessibilityevent.type_view_clicked) is sent after the finger leaves the screen;    return result;}
        Not sure what we expected, in the PerformClick () method, if Li.monclicklistener is not null, the OnClick () method is called. The careful child boots should be found at the end of the PerformClick () method called the Sendaccessibilityevent () method, which is the method of the view implementation Accessibilityeventsource interface, That is, when the VIEW is clicked, it sends a secondary event of type accessibilityevent.type_view_clicked to the system, thus guessing that a secondary event message will be sent to the system when the Click event occurs. When the system receives this message, it will callback the Onaccessibilityevent () method of the various Accessibilityservice services registered into the system. Along with this speculation we continue to follow the Sendaccessibilityevent () method, found that the method is ultimately called the Sendaccessibilityeventuncheckedinternal () method, the source of the method is as follows:
public        void Sendaccessibilityeventuncheckedinternal (Accessibilityevent event) {if (!isshown ()) {//If the current view is not visible, return directly    Return }//Initialize event events, such as setting source,classname,packagename,enabled,contentdescription and so on oninitializeaccessibilityevent (    event);    Only a subset of accessibility events populates text content. if ((Event.geteventtype () & populating_accessibility_event_types)! = 0) {dispatchpopulateaccessibilityevent (EV    ENT);    }//In the beginning we called #isShown (), so we know that getParent () are NOT null. It is important to note here that the GetParent () method calls GetParent () for recursion. Requestsendaccessibilityevent (this, event);} 
The Requestsendaccessibilityevent () method of GetParent () is called after a series of processing of the event in the Sendaccessibilityeventuncheckedinternal () method, In the view system, the GetParent () method is a recursive call, usually returning the current view of the ViewGroup, I just started to think that the final call is the view root node of the Requestsendaccessibilityevent () method, In this article, it is said that the root view of the current window is Decorview, and then entered Decorview did not find the method, and follow-up viewgroup and view did not find the method, so you can be sure GetParent () The final return value is not a view, Through the data obtained the conclusion GetParent () eventually returns the Viewrootimpl instance object, which is the Requestsendaccessibilityevent () method that eventually calls Viewrootimpl, as shown below:
@Overridepublic Boolean requestsendaccessibilityevent (View Child, Accessibilityevent event) {    if (MView = = NULL | | mS topped | | mpausedfortransition) {        return false;    }    // ...... Omit part of the code        ... Maccessibilitymanager.sendaccessibilityevent (event);    return true;}
        requestsendaccessibilityevent in Viewrootimpl () The method also calls the Accessibilitymanager sendaccessibilityevent () method, that is, the event is ultimately sent through Accessibilitymanager, we then enter the method to see, the source code is as follows:
public void Sendaccessibilityevent (Accessibilityevent event) {final Iaccessibilitymanager service;    final int userId;        Synchronized (mLock) {service = getservicelocked ();        if (service = = null) {//service is null and returns return directly; } if (!misenabled) {throw new illegalstateexception ("accessibility off.        Did you forget to check that? ");}    UserId = Muserid;    } Boolean dorecycle = false;        try {event.seteventtime (Systemclock.uptimemillis ());        Long Identitytoken = Binder.clearcallingidentity (); Call Iaccessibilitymanager's Sendaccessibilityevent () method to send a secondary event dorecycle = Service.sendaccessibilityevent (event, UserI        D);        Binder.restorecallingidentity (Identitytoken);        if (DEBUG) {log.i (Log_tag, event + "sent");    }} catch (RemoteException re) {LOG.E (Log_tag, "Error during sending" + Event + "", re);            } finally {if (dorecycle) {Event.recycle (); }    }}
        sendaccessibilityevent in Accessibilitymanager () The Sendaccessibilityevent () method of the Iaccessibilitymanager instance object is called by the method to send the event, and who is Iaccessibilitymanger? From the above source know Iaccessibilitymanager is obtained through the getservicelocked () method, the source code is as follows:
private        Iaccessibilitymanager getservicelocked () {if (Mservice = = null) {///if Mservice is null, attempts to reinitialize the Mservice object    Tryconnecttoservicelocked (); } return mservice;} private void tryconnecttoservicelocked () {//ServiceManager gets the corresponding IBinder object IBinder IBinder = Servicemanager.getser    Vice (Context.accessibility_service);    if (IBinder = = null) {//If NULL is returned directly, no return is sent at this time; }//This step shows the conversion of a Iaccessibilitymanager service instance according to IBinder Iaccessibilitymanager service = IAccessibilityManager.Stub.asInte    Rface (IBinder);        try {final int stateflags = Service.addclient (mclient, Muserid);        Setstatelocked (StateFlags);    Mservice = Service;    } catch (RemoteException re) {LOG.E (Log_tag, "Accessibilitymanagerservice is Dead", re); }}

The Mservice is checked in the getservicelocked () method, and if NULL is called the tryconnecttoservicelocked () method, the tryconnecttoservicelocked () Method calls the Servicemanager.getservice () method to get a IBinder object, it is important to note that Servicemanger is the heavyweight daemon in the Android system, which is started after the Init process is started, It is used to manage various system services (such as inputmethodservice,activitymanagerservice, etc.) that are common to Android systems and to provide client with the ability to query the relevant service. This blog post has a detailed explanation of ServiceManager. After the service has been obtained, a secondary event message is passed to the system through the service, and then the system receives the secondary event message and finds the relevant Accessibilityservice based on the package name of the event. If you find it, you call Accessibilityservice's Onaccessibilityevent () method and pass the auxiliary event in, summing up the available instructions:

Well, according to the above flowchart we basically clarify the accessibilityservice operation process, mainly is the target app process to send messages to the system process, the system process received the message and then send the message to the relevant target Accessibilityservice, The main process is these, if there are small partners want to understand how the system process is to pass the message to the target service, because there is too much code to analyze here is no longer write down, please small partners privately find the relevant information.

To here about the use of accessibilityservice to build their own app small plug-in is an end, familiar with the principle after we can make their own favorite small plug, need to pay attention to the production of small plug should be reasonable, do not do external adverse things, finally thanks to watch ( *^__^*) ...






Android Source Series < 11 > from the perspective of the source of deep understanding Accessibilityservice, to create their own app small plug (bottom)

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.