Android Primer (18) Service

Source: Internet
Author: User

Original link: http://www.orlion.ga/674/

First, define a service

Create a project Servicedemo, and then add a class named MyService to this project, and let it inherit from the Service, and the finished code looks like this:

public class MyService extends Service {@Override public ibinder onbind (Intent Intent) {return null; }}

The Onbind () method is the only abstract method in the service that can now be temporarily ignored. Since the definition of a service, nature should be in the service to deal with some things, the logic to deal with things should be written where? You can then rewrite some of the other methods in the service as follows:

public class myservice extends service {      @Override     public ibinder onbind (intent intent)  {         return null;    }      @Override     public void oncreate ()  {         super.oncreate ();    }     @Override      public int onstartcommand (Intent intent, int flags, int startid )  {        return super.onstartcommand (Intent, flags,  startid);    }     @Override     public  Void ondestroy ()  {        super.ondestroy ();     }} 

As you can see, here we rewrite the three methods of OnCreate (), Onstartcommand () and OnDestroy (), which are the three most commonly used methods in each service. where the OnCreate () method is called when the service is created, the Onstartcommand () method is invoked every time the service is started, and the OnDestroy () method is called when the service is destroyed.

Normally, if we want the service to execute an action as soon as it is started, we can write the logic in the Onstartcommand () method. And when the service is destroyed, we should reclaim those resources that are no longer used in the OnDestroy () method.

Also need to note that each service needs to be registered in the Androidmanifest.xml file in order to take effect, do not know if you have found that this is the four components of Android common features. So we should also modify the Androidmanifest.xml file, as shown in the code below:

<application android:allowbackup= "true" android:icon= "@drawable/ic_launcher" android:label= "@string/app_name" Android:theme= "@style/apptheme" > ... <service android:name= ". MyService "> </service></application>

Second, start and stop the service

Once you have defined the service, you should consider how to start and stop the service. Starting and Stopping methods of course you will not be unfamiliar, mainly through the use of intent to achieve, let us in the Servicetest project to try to start and stop myservice this service. First modify the code in Activity_main.xml, and add the two buttons as follows:

<linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android" android:layout_width= "Match_ Parent "android:layout_height=" match_parent "android:orientation=" vertical " >     <button        android:id= "@+id/start_service"          android:layout_width= "Match_parent"          android:layout_height= "Wrap_content"         android:text= "Start  service " />        <Button         android:id= "@+id/stop_service"         android: Layout_width= "Match_parent"         android:layout_height= "wrap_content "        android:text=" Stop service " /></LinearLayout >

     then modify the code in Mainactivity as follows:

Package ga.orlion.servicedemo;import android.app.activity;import android.content.intent;import  android.os.Bundle;import android.view.Menu;import android.view.MenuItem;import  android.view.view;import android.view.view.onclicklistener;import android.widget.button;public  Class mainactivity extends activity implements onclicklistener{private button  startService;private Button stopService; @Overrideprotected  void oncreate (Bundle  savedinstancestate)  {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); startservice =  (Button)  findviewbyid (r.id.start_service);stopservice =  (button)   Findviewbyid (R.id.stop_service); Startservice.setonclicklistener (this); Stopservice.setonclicklistener (this);} @Overridepublic  void onclick (view v)  {switch  (V.getid ())  {case r.id.start_ service:intent startintent  = new intent (This , myservice.class); StartService (startintent); break;case R.id.stop_ Service:intent stopintent = new intent (This , myservice.class); StopService ( stopintent); break;default:break;}}}

As you can see, there are instances of the Start service button and the Stop service button are obtained in the OnCreate () method, and the click events are registered with them. Then, in the Click event of the Start Service button, we built a intent object and called the StartService () method to start the MyService service. In the Click event of the Stop Serivce button, we also built a intent object and called the StopService () method to stop myservice the service. Both the StartService () and the StopService () methods are defined in the context class, so we can invoke both methods directly in the activity. Note that it is entirely up to the activity to determine when the service is stopped, and if you do not click the Stop Service button, the service will remain in the running state. Is there any way for the service to stop itself? Of course, you just have to call the Stopself () method at any point in the MyService to stop the service.

Then there is another problem to think about, how can we verify that the service has been successfully started or stopped? The simplest approach is to include the print log in several methods of MyService, as follows:

Package Ga.orlion.servicedemo;import Android.app.service;import Android.content.intent;import android.os.IBinder; Import Android.util.log;public class MyService extends Service {@Overridepublic ibinder onbind (Intent Intent) {return nul l;} @Overridepublic void OnCreate () {super.oncreate (); LOG.D ("MyService", "onCreate");} @Overridepublic int Onstartcommand (Intent Intent, int flags, int startid) {log.d ("MyService", "Onstartcommand"); return Super.onstartcommand (Intent, flags, Startid);} @Overridepublic void OnDestroy () {Super.ondestroy (); LOG.D ("MyService", "OnDestroy");}}

III. Activities and Service communications

Although the service is started in the activity, but after starting the service, the activity and the service basically has no relationship. So is there any way to make activities and services more closely related? For example, in the event of directing the service to do, the service to do. Of course, this requires the use of the Onbind () method that we have just overlooked. For example, at present we want to provide a download function in MyService, and then in the event can decide when to start the download, and to view the download progress at any time. The idea for this is to create a dedicated binder object to manage the download functionality and modify the code in MyService as follows:

... public class MyService extends Service {private Downloadbinder Mbinder = new Downloadbinder (); class Downloadbinder Exte NDS Binder {public void Startdownload () {log.d ("MyService", "Start Download");} public int getprogress () {log.d ("MyService", "Get Progress"); return 0;}} @Overridepublic ibinder onbind (Intent Intent) {return mbinder;} ...}

     can see, here we create a new Downloadbinder class and let it inherit from Binder, and then inside it provides a way to start the download and view the download progress. Of course, this is only two simulation methods, and does not implement the real function, we in the two methods to print a row of logs. Next, an instance of Downloadbinder was created in MyService and then returned in the Onbind () method, so that the work in MyService is complete. Here's a look at how to invoke these methods in the service in the event. First you need to add two buttons to the layout file to modify the code in the Activity_main.xml as follows:

<button android:id= "@+id/bind_service" android:layout_width= "Match_parent" android:layout_height= " Wrap_content "android:text=" Bind Service "/> <button android:id=" @+id/unbind_service "an Droid:layout_width= "Match_parent" android:layout_height= "wrap_content" android:text= "Unbind Service"/>

     These two buttons are used to bind the service and unbind the service, then who needs to go and service binding? Of course it's the activity. When an activity and service are bound, it is possible to invoke the methods provided by the binder in the service. Modify the code in the mainactivity as follows:

package ga.orlion.servicedemo;import android.app.activity;import android.content.componentname; Import android.content.intent;import android.content.serviceconnection;import android.os.bundle ;import android.os.ibinder;import android.view.menu;import android.view.menuitem;import  android.view.view;import android.view.view.onclicklistener;import android.widget.button;public  Class mainactivity extends activity implements onclicklistener{private button  startService;private Button stopService;private Button bindService;private  button unbindservice;private myservice.downloadbinder downloadbinder;private  Serviceconnection connection = new serviceconnection ()  {@Overridepublic  void  onserviceconnected (Componentname name, ibinder service)  {downloadBinder =  (Myservice.downloadbinder)  servIce;downloadbinder.startdownload ();d ownloadbinder.getprogress ();} @Overridepublic  void onservicedisconnected (componentname name)  {}}; @Overrideprotected  void oncreate (bundle savedinstancestate)  {super.oncreate (savedInstanceState); Setcontentview (R.layout.activity_main);startservice =  (Button)  findviewbyid (R.id.start_service) ;stopservice =  (Button)  findviewbyid (R.id.stop_service); Startservice.setonclicklistener (this); Stopservice.setonclicklistener (This);bindservice =  (Button)  findviewbyid (R.id.bind_service); unbindservice =  (Button)  findviewbyid (R.id.unbind_service); Bindservice.setonclicklistener (This) ; Unbindservice.setonclicklistener (this);} @Overridepublic  void onclick (view v)  {switch  (V.getid ())  {case r.id.start_ Service:intent startintent = new intent (This , myservice.class); StartService ( startintent); break;case r.id.stop_Service:intent stopintent = new intent (This , myservice.class); StopService ( stopintent); Break;case r.id.bind_service:intent bindintent = new intent (this ,  myservice.class); Bindservice (bindintent , connection , bind_auto_create);  //   BIND service Break;case r.id.unbind_service:unbindservice (connection); //  unbind service Break;default:break;}}}

As you can see, here we first create an anonymous class of Serviceconnection, which overrides the Onserviceconnected () method and the Onservicedisconnected () method, These two methods are called when the activity and the service are successfully bound and unbound. In the Onserviceconnected () method, we also get an example of downloadbinder by downward transformation, and with this example, the relationship between the activity and the service becomes very close. Now we can invoke any public method in the activity based on a specific scenario, that is, the function of what the command service does and what the service will do Downloadbinder. This is still a simple test, and the Downloadbinder startdownload () and Getprogress () methods are called in the Onserviceconnected () method.

Of course, activities and services are not yet binding, and this feature is done in the BIND Service button's Click event. As you can see, we're still building a intent object, and then calling the Bindservice () method to bind Mainactivity and MyService. The Bindservice () method receives three parameters, the first parameter is the intent object that was just built, the second argument is an instance of the Serviceconnection created earlier, and the third parameter is a flag bit, which is passed in Bind_auto_ Create means that the service is created automatically after the activity and the service are bound. This will cause the OnCreate () method in MyService to be executed, but the Onstartcommand () method will not execute. And what if we want to unbind the activity from the service? Call the Unbindservice () method, which is the function that is implemented in the Click event of the Unbind service button.

Iv. Life cycle of services

Once the context's StartService () method is called at any point in the project, the corresponding service will start up and callback the Onstartcommand () method. If the service has not been created before, the OnCreate () method will be executed prior to the Onstartcommand () method. After the service is started, it remains running until the StopService () or Stopself () method is called. Note that while the StartService () method is called every time, Onstartcommand () executes

Once, but there is actually only one instance for each service. So no matter how many times you call the StartService () method, simply call the StopService () or Stopself () method and the service will stop. Alternatively, you can call the context's Bindservice () to get a persistent connection to a service, and then callback the Onbind () method in the service. Similarly, if the service has not been created before, the OnCreate () method is executed before the Onbind () method. The caller can then obtain an instance of the IBinder object returned in the Onbind () method so that it can communicate freely with the service. As long as the connection between the caller and the service is not broken, the service remains in a running state.

When the StartService () method is called and the StopService () method is called, the OnDestroy () method in the service executes, indicating that the service has been destroyed. Similarly, when the Bindservice () method is called and the Unbindservice () method is called, the OnDestroy () method executes, both of which are well understood. However, it is important to note that it is entirely possible for a service to call both the StartService () method and the Bindservice () method, so how can the service be destroyed? Depending on the mechanism of the Android system, a service can be destroyed only after it has been started or bound, and it has been in a state of operation and must not satisfy both of these conditions. Therefore, the OnDestroy () method executes when the StopService () and Unbindservice () methods are called simultaneously in this case.

Android Primer (18) Service

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.