Android Development Service Details

Source: Internet
Author: User

Service as one of the four components of Android, it is important to imagine, in the development, we often do not need to interact with users in the service to complete, service running in the background, so that some people may have an illusion, Because the service is running in a new thread, it is not, the service is running in the main threads, so it is not time consuming in the service, otherwise it will report the ANR exception, but we can take the time-consuming operation in the service, such as downloading and so on.

First of all, the two binding methods of service, one is through Context.startservice () to start, and the other is the way of binding, through the Bindservice method to achieve.

First startup mode: We typically start the service in the OnStart () method (using Method StartService () or Bindservice ()) and stop the service in the OnStop method (using Method StopService () or Unbindservice ()).

Let's take a look at the first type:

 Public  class MyService1 extends Service {    @Override     Public void onCreate() {LOG.I ("Lenve","OnCreate ()"); Sendmsg2activity ("Service Creation"); }//Obsolete method, no longer used    @Override     Public void OnStart(Intent Intent,intStartid) {Super. OnStart (Intent, Startid); LOG.I ("Lenve","OnStart ()"); }@Override     Public int Onstartcommand(Intent Intent,intFlagsintStartid) {LOG.I ("Lenve","Onstartcommand ()");return Super. Onstartcommand (Intent, flags, Startid); }Private void sendmsg2activity(String string) {Intent Intent =NewIntent ("Service2activity"); Intent.putextra ("MSG", string); This. Sendbroadcast (Intent); }@Override     Public void OnDestroy() {Super. OnDestroy (); LOG.I ("Lenve","OnDestroy ()"); }@Override     PublicIBinderOnbind(Intent Intent) {LOG.I ("Lenve","Onbind ()");return NULL; }}

Start Service in activity

new Intent(this, MyService1.class);startService(intent);

Stop Service

stopService(intent);

By printing the log we can see that the first call to service will trigger the OnCreate () method, and subsequent calls will no longer execute the OnCreate () method, no matter how many times we start the service, it has only one, that is, stop the service only once.

Second, the service is started by binding

If you want to subdivide this type of startup is divided into two types:
1. Design the interface and implement the interface through IBinder to expose the activity to its invocation.
Interface:

publicinterface MyServiceInterface {    publicintadd(int a,int b);}

Myservice.java

 Public  class MyService1 extends Service {    PrivateIBinder Mybinder =NewMybinder (); Public  class mybinder extends Binder implements Myserviceinterface {        @Override         Public int Add(intAintb) {returnA+b; }    }@Override     PublicIBinderOnbind(Intent Intent) {LOG.I ("Lenve","Onbind ()");returnMybinder; }@Override     Public void onCreate() {Super. OnCreate (); LOG.I ("Lenve","OnCreate ()"); Mybinder =NewMybinder (); }@Override     Public void OnDestroy() {Super. OnDestroy (); LOG.I ("Lenve","OnDestroy ()"); }@Override     Public Boolean Onunbind(Intent Intent) {LOG.I ("Lenve","Onunbind ()");return Super. Onunbind (Intent); }@Override     Public void Onrebind(Intent Intent) {Super. Onrebind (Intent); LOG.I ("Lenve","Onrebind ()"); }}

Start the service in activity and call the Add method:

 Public  class mainactivity extends Activity {    PrivateTextView TV1;PrivateServiceconnection Conn;PrivateIntent Intent;PrivateMyserviceinterface MSI;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main); TV1 = (TextView) This. Findviewbyid (R.id.textview1); Intent =NewIntent ( This, Myservice1.class); LOG.I ("Lenve",""+1); conn =NewServiceconnection () {//Call when connection is interrupted            @Override             Public void onservicedisconnected(componentname name) {            }//Call when connection succeeds            @Override             Public void onserviceconnected(componentname name, IBinder service)                {msi = (myserviceinterface) service; LOG.I ("Lenve","The connection was successful!" ");        }        };    Bindservice (Intent, Conn, bind_auto_create); } Public void OnClick(View v) {Switch(V.getid ()) { CaseR.id.button1:tv1.settext (Msi.add (4,5) +""); Break;default: Break; }    }@Override    protected void OnStop() {Super. OnStop ();    Unbindservice (conn); }}

Through the interface, we can invoke the methods in the service in the activity, thus realizing the communication between the two.

2. Returns the binder in Onbinder (), and returns the current service object directly in the class that inherits binder, invoking the method exposed in the service through the service object.

Service Code

 Public  class MyService2 extends Service {    PrivateIBinder Mybinder =NewMybinder (); Public  class mybinder extends Binder {         PublicMyService2GetService() {returnMyService2. This; }    }@Override     PublicIBinderOnbind(Intent Intent) {LOG.I ("Lenve","Onbind ()");returnMybinder; }@Override     Public void onCreate() {Super. OnCreate (); LOG.I ("Lenve","OnCreate ()"); Mybinder =NewMybinder (); }@Override     Public void OnDestroy() {Super. OnDestroy (); LOG.I ("Lenve","OnDestroy ()"); }@Override     Public Boolean Onunbind(Intent Intent) {LOG.I ("Lenve","Onunbind ()");return Super. Onunbind (Intent); }@Override     Public void Onrebind(Intent Intent) {Super. Onrebind (Intent); LOG.I ("Lenve","Onrebind ()"); } Public int minus(intAintb) {returnA-B; }}

Binding in activity:

 Public  class mainactivity extends Activity {    PrivateTextView TV1;PrivateServiceconnection Conn;PrivateIntent Intent;PrivateMyService2 MS2;PrivateMyserviceinterface MSI;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main); TV1 = (TextView) This. Findviewbyid (R.id.textview1);//Intent = new Intent (this, myservice1.class);Intent =NewIntent ( This, Myservice2.class); conn =NewServiceconnection () {//Call when connection is interrupted            @Override             Public void onservicedisconnected(componentname name) {            }//Call when connection succeeds            @Override             Public void onserviceconnected(componentname name, IBinder service) {//msi = (myserviceinterface) service;                //Get the current service objectMybinder MB = (mybinder) service;                MS2 = Mb.getservice (); LOG.I ("Lenve","The connection was successful!" ");        }        }; Bindservice (Intent, Conn, bind_auto_create);//New Thread (new Runnable () {////@Override//public void Run () {//try {//Thread.Sleep (+);//Tv1.settext (Msi.add (4, 5) + "");//} catch (Interruptedexception e) {//E.printstacktrace ();//              }//          }//      }). Start ();} Public void OnClick(View v) {Switch(V.getid ()) { CaseR.id.button1://Direct call to public method in serviceTv1.settext (Ms2.minus (9,6)+"");//Tv1.settext (Msi.add (4, 5) + "");             Break;default: Break; }    }@Override    protected void OnStop() {Super. OnStop ();    Unbindservice (conn); }}

Personally think the second way is better, not only easy, but also more convenient interaction.

In fact, if you want to achieve communication between service and activity, you can also use broadcast.

The more advanced aidl we tell.

This sample code download Http://pan.baidu.com/s/1sjupRZZ

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced. If there is a wrong place, I would appreciate it if I could criticize it.

Android Development Service Details

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.