An analysis of the mechanism of Android binder

Source: Internet
Author: User

Binder mechanism is An important means of cross-process communication in Android system. the interaction betweenService and Activity is used in this mechanism. To this end, I have written a small service case, in order to facilitate a better understanding of binder communication mechanism.

Service Code:

 Public classMyServiceextendsService { Public Booleanflag=true; intcount; //Instantiate a binderServicebinder servicebinder=NewServicebinder (); Private Static FinalString TAG = "MyService"; @Override Public voidonCreate () {LOG.I ("Winer", "MyService is oncreate!"); //Create a thread that continuously outputs the change of the count variable        NewThread (NewRunnable () { Public voidrun () { while(true) {                    Try{Thread.Sleep (1000); } Catch(Interruptedexception e) {}//flag is True then count is self-added                    if(flag) Count++; //flag is flase and count is self-reduced                    ElseCount--; //Output CountLOG.I ("MyService", "Count is" +count);    }}). Start (); } @Override Public BooleanOnunbind (Intent Intent) {log.i ("Winer", "MyService is onunbind!"); return Super. Onunbind (Intent); } @Nullable @Override Publicibinder onbind (Intent Intent) {log.i ("Winer", "MyService is onbind!"); //Back to Binder        returnServicebinder; } @Override Public voidOnDestroy () {LOG.I ("Winer", "MyService is ondestroy!"); Super. OnDestroy (); }//binder structure, for communication    classServicebinderextendsBinder { PublicMyService GetService () {returnMyService. This; }} @Override Public intOnstartcommand (Intent Intent,intFlagsintStartid) {LOG.I ("Winer", "MyService is onstartcommand!"); return Super. Onstartcommand (Intent, flags, Startid); }}
View Code

  Mainactivity Code:

 Public classMainactivityextendsappcompatactivity {Button startbtn,changebtn;    MyService MyService; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); //Create the intent required to start the service        FinalIntent i =NewIntent ( This, MyService.class); CHANGEBTN=(Button) Findviewbyid (R.ID.CHANGE_BTN); STARTBTN=(Button) Findviewbyid (R.ID.START_BTN); Startbtn.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {//Create and bind a serviceBindservice (I,Newserviceconnection () {@Override//What you do after a service connection                     Public voidonserviceconnected (componentname name, IBinder service) {//Obtain the flag variable that the service uses to access the service through BinderMyService =( (Myservice.servicebinder) service). GetService (); //Use the button to change flagChangebtn.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {if(!myservice.flag) Myservice.flag=true; ElseMyservice.flag=false;                    }                        }); } @Override//accidental Disconnection (the code will not execute if the program exits gracefully)                     Public voidonservicedisconnected (componentname name) {}}, context.bind_auto_create);    }        }); }}
View Code

Finally, don't forget to register the service in manifest.

Before we get to the binder, we need to know what the service is. Service is an Android services component, similar to a non-interface activity, often used for time-consuming service processes such as music player, downloader, etc. We know that there is no way to communicate data directly between activity and activity. We need to use the intent (Binder mechanism's encapsulation) to transmit data. The specific way to call Intent.putextra (...) method to put the activity into the intent. After startup, the new activity retrieves the data again. Of course, this approach also applies to starting the service. Unlike activity, the actual application of service to activity is more frequent. For example, music player may need to send the music service to play, pause, switch, fast forward and so on, the service should return to the playback progress and other information in time. Therefore, this way of using intent to pass data is obviously inappropriate. As a result, Android uses a binder mechanism to pass information directly. For example, the above code, mainactivity is such a myservice flag variable:

1. The binder variable is obtained by the onserviceconnected callback function in the Serviceconnection instance of the parameter of the Bindservice method.

2. Get the MyService instance through the return value in the Binder class.

Binder is like a bridge between service and activity. The activity obtains the binder instance first, and then uses the binder instance to obtain the service instance.

Let's take a look at the implementation of its internal logic:

TinyMCE

An analysis of the mechanism of Android binder

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.