Android Service Component Detailed _android

Source: Internet
Author: User

Service components are similar to activity components and can be said that service is an activity with no interface,

Of course, the life cycle of service and activity is still a certain difference.

Service components are generally used where the service component has no interface, no direct interaction with the user,

So service components are generally running in the background. For example, do not need the interface of data processing and so on.

There are two steps to develop a service:

1, define a subclass of the base service.
2, configure the service in the Androidmanifest.xml file.

How to start a service, think of two ways to start an activity:

StartActivity (Intent),
Startactivityforresult (Intent)

Then there are two ways to start a service:

StartService (Intent),
Bindservice (Intent service,serviceconnection conn,int flags),

What's the difference? You can look at the following code first:

public class Bindservice extends Service {private int count;
  Private Boolean quit;
  Defines the object returned by the Onbinder method private Mybinder binder = new Mybinder (); Implement the IBinder class public class Mybinder extends Binder {public int getcount () {//Get service run by inheriting Binder
    State: Count return count;
    The method that must be implemented @Override public IBinder onbind (Intent Intent) {System.out.println (' Service is binded ');
  Returns the IBinder object return binder;
  The method is invoked when the service is created.
    @Override public void OnCreate () {super.oncreate ();
    System.out.println ("Service is Created");
        Start a thread, dynamically modify the Count state value new thread () {@Override public void run () {while (!quit)
          {try {thread.sleep (1000);
        catch (Interruptedexception e) {} count++;    
  }}.start (); The callback method @Override public boolean onunbind (Intent) When the service is disconnected Intent) {System.out.println ("Service is unbinded");
  return true;
  }//service is closed before callback.
    @Override public void OnDestroy () {Super.ondestroy ();
    This.quit = true;
  System.out.println ("Service is destroyed");
    @Override public void Onrebind (Intent Intent) {super.onrebind (Intent);
    This.quit = true;
  System.out.println ("Service is rebinded");
 }  
}

The function of the service above is simply to open a thread, every 1 seconds count++, this count data
Passed to the visitor through the binder object.

To be done later, see how the following code starts the service and gets count data for the service

public class Mainactivity extends activity {Button startservice_bnt, bindservice_bnt;
 
  Keep the IBinder object of the service started Bindservice.mybinder binder;
    @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
 
    Setcontentview (R.layout.main);
    STARTSERVICE_BNT = (Button) Findviewbyid (R.ID.START_BNT);
 
    BINDSERVICE_BNT = (Button) Findviewbyid (R.ID.BIND_BNT);
 
     Create the Intent Intent Intent = new Intent (This,bindservice.class) that initiates the service;
      Startservice_bnt.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View source)
      {//binding specifies SERIVCE StartService (intent);  
    
    }
    });
      Bindservice_bnt.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View source)  
        
        {//binding specifies Serivce Bindservice (intent, Conn, service.bind_auto_create); Toast.maketext (Mainactivity.this, "Serivce's CThe Ount value is: "+ binder.getcount (), 4000). Show ();
 
 
  }
    }); }//define a Serviceconnection object private serviceconnection conn = new Serviceconnection () {//When the activity and servi Callback This method when the CE connection succeeds @Override public void onserviceconnected (componentname name, IBinder service) {Syst
      Em.out.println ("--service connected--");
    Gets the Mybinder object binder = (bindservice.mybinder) service returned by the Onbind method of the service;
      //When the activity is disconnected from the service @Override public void onservicedisconnected (componentname name) {      
    System.out.println ("--service disconnected--");
}
  };
 }

The activity above defines two buttons, and clicking two buttons has two different ways to start the service:

 StartService (Intent),
 Bindservice (Intent service,serviceconnection conn,int flags),
 

Now let's talk about the difference between the two startup modes and explain the code above.

startService(intent)Start the service. It does not have the ability to interact with the visitor, just as it does in an activity that startActivity(), does not have a new start to get the data back.

and Bindservice (Intent service,serviceconnection conn,int flags), it's not the same.

Visitors can get the data from the starting service, how to get it, Bindservice's second parameter conn, the parameter is a Serviceconnection object, when the visitor and service connection succeeds The onserviceconnected () method of Serviceconnection is called back, and the above procedure is to get the IBinder object in the callback method.

Can take a look at

Defines a Serviceconnection object
  private Serviceconnection conn = new Serviceconnection ()
  {
    // Callback This method
    @Override public
    void onserviceconnected (componentname name
      , IBinder when the activity is successful with the service connection) Service)
    {
      System.out.println ("--service connected--");
      Gets the Mybinder object
      binder = (bindservice.mybinder) service returned by the Onbind method of the service;
    Callback this method when the activity is disconnected from the service
    @Override public
    void onservicedisconnected (componentname name)
    {
      System.out.println ("--service disconnected--");      
    }
  ;

The simple point is that the visitor binds to the Service through Bindservice, and the binding succeeds in calling back the Onserviceconnected () method in Serviceconnection, which has ibinder Service parameters, This parameter is the object that the service exposes to the visitor, and the visitor gets the object to access the service data.

This is the principle that the visitor interacts with the service data and is passed through the IBinder object.

Maybe here you are also to Binder = (bindservice.mybinder) service; This code does not understand.

You can feel the IBinder object should not be the above service code Onbind method return Binder is, how strong turn into Bindservice.mybinder object.

And the return of the binder also no count data, how visitors can Binder.getcount () to get the data.

@Override public
  IBinder onbind (Intent Intent)
  {
    System.out.println ("Service is binded");
    Returns the IBinder object return
    binder;
  }

Don't forget the IBinder object is also processed in the service code above.

The IBinder class public
  class Mybinder extends Binder
  {public
    int getcount ()
    {
      ///) is implemented by inheriting Binder. Gets the running status of the service: Count return
      count;
    }
  

Binder is the IBinder implementation class, Mybinder inherits Binder and defines a method inside it.

Then get the IBinder object is equivalent to get Mybinder object, you can access the GetCount method, which is why binder = (bindservice.mybinder) service; Make a strong turn, and Binder.getcount () can get the count data, because the ibinder inside does not have the business implementation, is mybinder to help it achieve.

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.