Android service life cycle and usage

Source: Internet
Author: User

Service Concept and use:
Android service, it is different from the activity, it is unable to interact with the user, can not start, run in the background of the program, if we quit the application, the service process is not finished, it is still running in the background, then when we will use the service? For example, when we play music, we may want to listen to music while doing some other things, when we quit playing music application, if we do not use the service, we can not hear the song, so this time we need to use the service, and for example, when our application data is obtained through the network, Different times (over time) the data is different at this time we can use the service in the background to update periodically, instead of every time we open the application to get.

Service life cycle:
The life cycle of Android service is not as complex as activity, it only inherits OnCreate (), OnStart (), OnDestroy () Three methods, when we first start the service, we call OnCreate (), OnStart () These two methods, when the service is stopped, the OnDestroy () method is executed, it is important to note that if the service has been started, when we start the service again, we will not execute the OnCreate () method, Instead, directly execute the OnStart () method, which can be seen in the following example.

Service communicates with activity:
The service backend data is ultimately presented on top of the front-end activity, because when the service is started, the system restarts a new process, which involves different interprocess communication issues (AIDL) This section I do not describe too much, When we want to get started service instances, we can use the Bindservice and Onbindservice methods, which perform the IBinder () and Onunbind () methods in the service respectively.
In order to make everyone easier to understand, I wrote a simple demo, you can imitate me, step by step.

First step: Create a new Android project, which I named Servicedemo.
Step Two: Modify the Main.xml code, I have added four buttons here, the code is as follows:

<?XML version= "1.0" encoding= "Utf-8"?>  <LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"android:orientation= "vertical"Android:layout_width= "Fill_parent"Android:layout_height= "Fill_parent"      >      <TextViewAndroid:id= "@+id/text"Android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"Android:text= "@string/hello"          />      <ButtonAndroid:id= "@+id/startservice"Android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"Android:text= "StartService"      />      <ButtonAndroid:id= "@+id/stopservice"Android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"Android:text= "StopService"      />      <ButtonAndroid:id= "@+id/bindservice"Android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"Android:text= "Bindservice"      />      <ButtonAndroid:id= "@+id/unbindservice"Android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"Android:text= "Unbindservice"      />  </LinearLayout>

Step three: Create a new service named Myservice.java code as follows:

Package Com.tutor.servicedemo;  Import Android.app.Service;  Import android.content.Intent;  Import Android.os.Binder;  Import Android.os.IBinder;  Import Android.text.format.Time;  Import Android.util.Log;      public class MyService extends Service {//define a tag tag private static final String tag = "MyService";      Here is the definition of a binder class, used in the Onbind () method, so that activity over there can be obtained to private mybinder Mbinder = new Mybinder ();          @Override public IBinder onbind (Intent Intent) {log.e (TAG, "Start ibinder~~~");      return mbinder;          } @Override public void OnCreate () {LOG.E (TAG, "Start oncreate~~~");      Super.oncreate ();          } @Override public void OnStart (Intent Intent, int startid) {log.e (TAG, "Start onstart~~~");       Super.onstart (Intent, Startid);          } @Override public void OnDestroy () {LOG.E (TAG, "Start ondestroy~~~");      Super.ondestroy (); } @Override Public BooleaN Onunbind (Intent Intent) {log.e (TAG, "Start onunbind~~~");      return Super.onunbind (Intent);          }//Here I've written a function to get the current time, but it's not formatted first. Public String GetSystemTime () {Time t = new Times ();          T.settonow ();      return t.tostring (); } public class Mybinder extends binder{myservice getService () {return myservice.          This }      }  }

Fourth step: Modify Servicedemo.java, the code is as follows:

 PackageCom.tutor.servicedemo; Importandroid.app.Activity; ImportAndroid.content.ComponentName; ImportAndroid.content.Context; Importandroid.content.Intent; Importandroid.content.ServiceConnection; ImportAndroid.os.Bundle; ImportAndroid.os.IBinder; ImportAndroid.view.View; ImportAndroid.view.View.OnClickListener; ImportAndroid.widget.Button; ImportAndroid.widget.TextView;  Public classServicedemoextendsActivityImplementsonclicklistener{PrivateMyService Mmyservice; PrivateTextView Mtextview; PrivateButton Startservicebutton; PrivateButton Stopservicebutton; PrivateButton Bindservicebutton; PrivateButton Unbindservicebutton; PrivateContext Mcontext; //it needs to use the serviceconnection in Context.bindservice and Context.unbindservice ().    PrivateServiceconnection mserviceconnection =Newserviceconnection () {//when I bindservice, let TextView show the return value of the GetSystemTime () method in MyService         Public voidonserviceconnected (componentname name, IBinder service) {//TODO auto-generated Method StubMmyservice =( (Myservice.mybinder) service). GetService (); Mtextview.settext ("I am Frome Service:" +mmyservice.getsystemtime ()); }               Public voidonservicedisconnected (componentname name) {//TODO auto-generated Method Stub        }      };  Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);          Setcontentview (R.layout.main);      Setupviews (); }         Public voidsetupviews () {Mcontext= Servicedemo. This; Mtextview=(TextView) Findviewbyid (R.id.text); Startservicebutton=(Button) Findviewbyid (R.id.startservice); Stopservicebutton=(Button) Findviewbyid (R.id.stopservice); Bindservicebutton=(Button) Findviewbyid (R.id.bindservice); Unbindservicebutton=(Button) Findviewbyid (R.id.unbindservice); Startservicebutton.setonclicklistener ( This); Stopservicebutton.setonclicklistener ( This); Bindservicebutton.setonclicklistener ( This); Unbindservicebutton.setonclicklistener ( This); }       Public voidOnClick (View v) {//TODO auto-generated Method Stub        if(v = =Startservicebutton) {Intent I=NewIntent (); I.setclass (Servicedemo. This, MyService.class);          Mcontext.startservice (i); }Else if(v = =Stopservicebutton) {Intent I=NewIntent (); I.setclass (Servicedemo. This, MyService.class);          Mcontext.stopservice (i); }Else if(v = =Bindservicebutton) {Intent I=NewIntent (); I.setclass (Servicedemo. This, MyService.class);          Mcontext.bindservice (i, mserviceconnection, bind_auto_create); }Else{mcontext.unbindservice (mserviceconnection); }      }       }

Fifth step: Modify the Androidmanifest.xml code (register our new MyService)

<?XML version= "1.0" encoding= "Utf-8"?>  <Manifestxmlns:android= "Http://schemas.android.com/apk/res/android" Package= "Com.tutor.servicedemo"Android:versioncode= "1"Android:versionname= "1.0">      <ApplicationAndroid:icon= "@drawable/icon"Android:label= "@string/app_name">          <ActivityAndroid:name=". Servicedemo "Android:label= "@string/app_name">              <Intent-filter>                  <ActionAndroid:name= "Android.intent.action.MAIN" />                  <categoryAndroid:name= "Android.intent.category.LAUNCHER" />              </Intent-filter>          </Activity>          <ServiceAndroid:name=". MyService "android:exported= "true"></Service>      </Application>      <USES-SDKandroid:minsdkversion= "7" />  </Manifest>

The sixth step: the implementation of the above works, as follows:

Click on the Startservie button has executed the service OnCreate ()->onstart () These two methods, open the Logcat window effect such as:

We can then press the home key to enter settings (set)->applications (application)->running services (running service) look at our new launch of a service, the effect is as follows:

When you click the StopService button, the service executes the OnDestroy () method, as follows:

This time we click the StartService button again and then click the Bindservice button (usually Bindservice is the service that Bind has already started), we look at the service executed the IBinder () method, And the value of TextView has changed, as shown in the following two images:

Finally click the Unbindservice button, the service executes the Onunbind () method, as shown in

Android service life cycle and usage

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.