Android Service using Bindservice

Source: Internet
Author: User

The service has already been started by the StartServer way. You know, let's take a look at another way to get started with service →bindserver

Bindserver Usage Scenarios

1. Call between the same app (that is, in the same process)

2. Call between different apps (that is, inter-process communication)


Same app call (only one start of the service)

Binderacticitya

public class Binderacticitya extends Activity implements View.onclicklistener {private Button btn1;    Private Button btn2;    Private Button btn3;    Private Button Btn4;    Private Bindservice bindservice = null;    Private Boolean isbound = false; Private Serviceconnection conn = new Serviceconnection () {@Override public void onserviceconnected (Componen            Tname name, IBinder service) {Isbound = true;            Bindservice.mybinder binder = (bindservice.mybinder) service;            Bindservice = Binder.getservice ();            int num = Bindservice.getrandomnumber ();        LOG.V ("Hjz", "numa=" +num);            The method is called when//client and service connections are lost unexpectedly @Override public void onservicedisconnected (componentname name) {        LOG.V ("Hjz", "onservicedisconnected A");    }    };        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_binder_Main);        Findlayoutview ();        Setlister ();    InitData ();        } private void Findlayoutview () {btn1 = (Button) Findviewbyid (R.ID.BTN1);        BTN2 = (Button) Findviewbyid (R.ID.BTN2);        Btn3 = (Button) Findviewbyid (R.ID.BTN3);    Btn4 = (Button) Findviewbyid (R.ID.BTN4);        } private void Setlister () {Btn1.setonclicklistener (this);        Btn2.setonclicklistener (this);        Btn3.setonclicklistener (this);    Btn4.setonclicklistener (this);        private void InitData () {} @Override public void OnClick (View v) {Intent Intent = null; Switch (V.getid ()) {Case r.id.btn1:intent = new Intent (Binderacticitya.this, Bindservice.class)                ;                Intent.putextra ("from", "Activitya");                Bindservice (intent,conn,bind_auto_create);            Break                    Case R.id.btn2:if (isbound) {isbound = false; LOG.V ("Hjz", "acticityA is Unbindservice ");                Unbindservice (conn);            } break;                Case r.id.btn3:intent = new Intent (this, binderactivityb.class);                StartActivity (Intent);            Break                Case R.id.btn4:this.finish ();        Break        }} @Override protected void OnDestroy () {Super.ondestroy ();    LOG.I ("Hjz", "Activitya-OnDestroy"); }}


Xml

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "xmlns:tools=" Http://schemas.android.com/tools "android:layout_width=" Match_parent "android:layout_height = "Match_parent" android:paddingbottom= "@dimen/activity_vertical_margin" android:paddingleft= "@dimen/activity_ Horizontal_margin "android:paddingright=" @dimen/activity_horizontal_margin "android:paddingtop=" @dimen/activity_        Vertical_margin "android:orientation=" vertical "tools:context=" com.hh.servicedemo.MainActivity "> <button        Android:id= "@+id/btn1" android:layout_width= "wrap_content" android:layout_height= "Wrap_content"         android:text= "Binderservice binding"/> <button android:id= "@+id/btn2" android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" android:text= "Binderservice unbind"/> <button android:id= "@ +id/btn3 "Android:layout_width=" Wrap_coNtent "android:layout_height=" wrap_content "android:text=" Jump to Binderactivityb "/> <button Android Oid:id= "@+id/btn4" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" android:t ext= "Finish"/></linearlayout>


Binderservice

public class Bindservice extends Service {public class Mybinder extends binder{public bindservice getService ()        {return bindservice.this;    }}//The communication between the caller (client) and the service is implemented through binder private Mybinder binder = new Mybinder ();    Private final random generator = new random ();        @Override public void OnCreate () {super.oncreate ();    LOG.I ("Hjz", "Bindservice-OnCreate, Thread:" + thread.currentthread (). GetName ()); } @Override Public IBinder onbind (Intent Intent) {log.i ("HJZ", "Bindservice-onbind, Thread:" + Thread        . CurrentThread (). GetName ());    return binder; } @Override public boolean onunbind (Intent Intent) {log.i ("HJZ", "Bindservice-Onunbind, from:" + inten        T.getstringextra ("from"));    return false; } @Override public int onstartcommand (Intent Intent, int flags, int startid) {log.i ("HJZ", "Bindservice-&gt ; Onstartcommand, Startid: "+ Startid +", Thread: " + Thread.CurrentThread (). GetName ());    return start_not_sticky; } @Override public void OnDestroy () {log.i ("HJZ", "Bindservice-OnDestroy, Thread:" + thread.currentth        Read (). GetName ());    Super.ondestroy ();    }//method exposed in service for client to call public int getrandomnumber () {return generator.nextint (); }}

Click Binderservice bindings, then click Binderservice to Unbind, finally click Finish, print the log

07-09 11:46:49.360 29714-29714/com.hh.servicedemo i/hjz:bindservice onCreate, thread:main07-09 11:46:49.360 29714-29714/com.hh.servicedemo I/hjz:bindservice, Onbind, thread:main07-09 11:46:49.380 29714-29714/ Com.hh.servicedemo v/hjz:numa=185923953907-09 11:46:50.650 29714-29714/com.hh.servicedemo V/hjz:acticitya is unbindservice07-09 11:46:50.650 29714-29714/com.hh.servicedemo i/hjz:bindservice onUnbind, from:ActivityA07-09 11:46:50.650 29714-29714/com.hh.servicedemo I/hjz:bindservice, OnDestroy, thread:main07-09 11:46:52.290 29714-29714/com.hh.servicedemo I/hjz:activitya-OnDestroy

Click Binderservice bindings, then click Finish

07-09 11:48:07.260 29714-29714/com.hh.servicedemo i/hjz:bindservice onCreate, thread:main07-09 11:48:07.260 29714-29714/com.hh.servicedemo I/hjz:bindservice, Onbind, thread:main07-09 11:48:07.270 29714-29714/ Com.hh.servicedemo v/hjz:numa=-34151049007-09 11:48:09.290 29714-29714/com.hh.servicedemo I/hjz:activitya ondestroy07-09 11:48:09.310 29714-29714/com.hh.servicedemo i/hjz:bindservice onunbind, from:ActivityA07-09 11:48:09.310 29714-29714/com.hh.servicedemo I/hjz:bindservice, OnDestroy, Thread:main


First from the Binderservice analysis, from the printing can be seen, first call OnCreate, and then in the call Onbind method, you will find the use of Binderstart to start, Onstartcommand This method does not invoke; Execution order in service:

1, first get the corresponding Binder object, you can use internal classes within the service to obtain the corresponding binder, as follows:

public class Mybinder extends binder{public        bindservice GetService () {            return bindservice.this;        }    }    The communication between the caller (client) and the service is implemented through binder    private mybinder binder = new Mybinder ();
2. Return the IBinder instance in the Onbind method, returning the instance either as the service instance itself or exposing the service public method through binder. Typically, the binder is made into the service inner class, and then a getservice-like method is created in the binder and the service object containing the binder is returned, as in the case above, This way, the client can get the corresponding service instance through this method


Then the process that the caller (client) executes

1. Create the Serviceconnetion instance first, and override its method, as shown below:

Create an instance of the Serviceconnection type    private Serviceconnection conn = new Serviceconnection () {        @Override public        void onserviceconnected (componentname name, IBinder service) {            Isbound = true;            Bindservice.mybinder binder = (bindservice.mybinder) service;            Bindservice = Binder.getservice ();            int num = Bindservice.getrandomnumber ();            LOG.V ("Hjz", "numa=" +num);        This method is called when the client and service connection is accidentally lost        @Override public        void onservicedisconnected (componentname name) {            LOG.V ("Hjz", "onservicedisconnected  A");        }    ;
This is because the object is used in Bindserver, Bindserver source

@Override Public    Boolean bindservice (Intent service, serviceconnection conn,            int flags) {//Call Bindserver, Find the second pass is the Serviceconnection object        return Mbase.bindservice (service, Conn, flags);    }

2, when the onserviceconnected callback is executed, we can get the service instance object through the IBinder instance or call the binder public method directly, thus realizing the connection between client and service.

3, the client and service is unbound, onservicedisconnected will not be called; Onservicedisconnected is invoked when the client and service connection is lost unexpectedly. Then the client and service must be disconnected.


Calls from the same app (this service is called multiple times)

Binderacivityb

public class Binderactivityb extends Activity implements View.onclicklistener {private Button btn1;    Private Button btn2;    Private Button Btn4;    Private Bindservice bindservice = null;    Private Boolean isbound = false; Private Serviceconnection conn = new Serviceconnection () {@Override public void onserviceconnected (Componen            Tname name, IBinder service) {Isbound = true;            Bindservice.mybinder binder = (bindservice.mybinder) service;            Bindservice = Binder.getservice ();            int num = Bindservice.getrandomnumber ();        LOG.V ("Hjz", "numb=" +num); } @Override public void onservicedisconnected (componentname name) {log.v ("HJZ", "Onservicedisconn        ected B ");    }    };        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_binder_b);        Findlayoutview ();        Setlister (); InitdatA ();        } private void Findlayoutview () {btn1 = (Button) Findviewbyid (R.ID.BTN1);        BTN2 = (Button) Findviewbyid (R.ID.BTN2);    Btn4 = (Button) Findviewbyid (R.ID.BTN4);        } private void Setlister () {Btn1.setonclicklistener (this);        Btn2.setonclicklistener (this);    Btn4.setonclicklistener (this);        private void InitData () {} @Override public void OnClick (View v) {Intent Intent = null; Switch (V.getid ()) {Case r.id.btn1:intent = new Intent (Binderactivityb.this, Bindservice.class)                ;                Intent.putextra ("from", "activityb");                Bindservice (intent,conn,bind_auto_create);            Break                    Case R.id.btn2:if (isbound) {isbound = false;                    LOG.V ("Hjz", "Acticityb is Unbindservice");                Unbindservice (conn);            } break; Case R.id.btn4:this.finiSH ();        Break        }} @Override protected void OnDestroy () {Super.ondestroy ();    LOG.I ("Hjz", "Activityb-OnDestroy"); }}
In Bindera, click Bindera bindings → jump binderacitivityb→binderb bind →binderb unbind →binderb Finish→bindera to unbind →bindera finish log

07-09 13:16:10.030 8593-8593/com.hh.servicedemo i/hjz:bindservice onCreate, thread:main07-09 13:16:10.030 8593-8593/com.hh.servicedemo I/hjz:bindservice, Onbind, thread:main07-09 13:16:10.050 8593-8593/ Com.hh.servicedemo v/hjz:numa=66506461407-09 13:16:13.650 8593-8593/com.hh.servicedemo v/hjz:numb=111646913307-09 13:16:16.550 8593-8593/com.hh.servicedemo v/hjz:acticityb is unbindservice07-09 13:16:18.680 8593-8593/ Com.hh.servicedemo i/hjz:activityb, ondestroy07-09 13:16:22.920 8593-8593/com.hh.servicedemo V/hjz:acticitya is unbindservice07-09 13:16:22.930 8593-8593/com.hh.servicedemo i/hjz:bindservice onUnbind, from:ActivityA07-09 13:16:22.950 8593-8593/com.hh.servicedemo I/hjz:bindservice, OnDestroy, thread:main07-09 13:16:25.660 8593-8593/ Com.hh.servicedemo I/hjz:activitya-OnDestroy

Found in the print log

In the case of a client calling service "same service":

If the service does not exist, the service execution order is oncreate→onbind, then the client creates the Serviceconnection instance and executes the Onserviceconnected method.

If the service is already running "instructions have been started elsewhere before", the IBinder instance is shared among all the client (clients) because the previously executed Onbind callback gets the IBinder instance. So the second execution of the Onbind callback, directly using the last acquired IBinder instance, and passed it to the corresponding onserviceconnected method, marking the connection has been established, At this point, there are two or more client (clients) and service bindings.

The client (clients) executes the Unbindservie process:

When the client and service are unbound, the service detects if it is also connected to other clients (the client) →

If not, the service executes the Onunbind method and then executes the OnDestroy method

If there is, the service does not execute the Onunbind and OnDestroy methods (which can be concluded from the printed log)


Click Bindera bindings → jump Binderacitivityb→binderb bind →binderb →binderb finish→bindera finish Log

07-09 13:19:58.340 8297-8297/com.hh.servicedemo i/hjz:bindservice onCreate, thread:main07-09 13:19:58.360 8297-8297/com.hh.servicedemo I/hjz:bindservice, Onbind, thread:main07-09 13:19:58.360 8297-8297/ Com.hh.servicedemo v/hjz:numa=202632154707-09 13:20:02.190 8297-8297/com.hh.servicedemo v/hjz:numb=- 158653056907-09 13:20:04.140 8297-8297/com.hh.servicedemo v/hjz:acticityb is unbindservice07-09 13:20:05.820 8297-8297/com.hh.servicedemo i/hjz:activityb, ondestroy07-09 13:20:07.080 8297-8297/com.hh.servicedemo I/HJZ: Activitya, ondestroy07-09 13:20:07.110 8297-8297/com.hh.servicedemo I/hjz:bindservice, OnUnbind, from: activitya07-09 13:20:07.110 8297-8297/com.hh.servicedemo i/hjz:bindservice OnDestroy, Thread:main

Conclusion: If client (client) execution (OnDestroy) is destroyed after client and service are connected through Bindserver, then client will automatically unbind the service.

Click Bindera bindings → Jump Binderacitivityb→binderb bindings →binderb finish→bindera unbind →bindera finish log
07-09 13:17:40.320 8297-8297/com.hh.servicedemo i/hjz:bindservice onCreate, thread:main07-09 13:17:40.320 8297-8297/com.hh.servicedemo I/hjz:bindservice, Onbind, thread:main07-09 13:17:40.340 8297-8297/ Com.hh.servicedemo v/hjz:numa=-111764560607-09 13:17:43.460 8297-8297/com.hh.servicedemo v/hjz:numb= 177434632207-09 13:17:44.770 8297-8297/com.hh.servicedemo i/hjz:activityb ondestroy07-09 13:17:56.780 8297-8297 /com.hh.servicedemo V/hjz:acticitya is unbindservice07-09 13:17:56.780 8297-8297/com.hh.servicedemo I/HJZ: Bindservice, Onunbind, from:activitya07-09 13:17:56.780 8297-8297/com.hh.servicedemo i/hjz:bindservice OnDestroy, thread:main07-09 13:17:58.060 8297-8297/com.hh.servicedemo I/hjz:activitya-OnDestroy

Click Bindera bindings → jump binderacitivityb→binderb bind →binderb Finish→bindera finish log

07-09 13:21:22.890 8297-8297/com.hh.servicedemo i/hjz:bindservice onCreate, thread:main07-09 13:21:22.890 8297-8297/com.hh.servicedemo I/hjz:bindservice, Onbind, thread:main07-09 13:21:22.900 8297-8297/ Com.hh.servicedemo v/hjz:numa=194732430807-09 13:21:26.630 8297-8297/com.hh.servicedemo v/hjz:numb=- 134364901307-09 13:21:27.730 8297-8297/com.hh.servicedemo i/hjz:activityb ondestroy07-09 13:21:29.040 8297-8297 /com.hh.servicedemo I/hjz:activitya, ondestroy07-09 13:21:29.060 8297-8297/com.hh.servicedemo i/hjz:bindservice Onunbind, from:activitya07-09 13:21:29.060 8297-8297/com.hh.servicedemo I/hjz:bindservice, Thread:main

The above log is printed with a graph below to summarize the client and service operation Flow:



Between the different apps call here do not introduce, interested in themselves can go to study


Android Service using Bindservice

Related Article

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.