"Alearning" chapter fifth introduction to Android related components (ii) Service

Source: Internet
Author: User

Service is one of the four components of Android, so it plays a very important role in the Android development process. Let's take a look at the official definition of service.

A Service is a application component Thatcan perform long-running operations in the background and does not provide auser inte Rface. Another application component can start a service and it willcontinue to run in the background even if the user switches T o anotherapplication. Additionally, a component can bind to a service to interact Withit and even perform interprocess communication (IPC). For example, a servicemight handle network transactions, play music, perform file I/O, or interactwith a content provider, all from the background.

The corresponding Chinese is: Service is an application component that runs in the background without a user interface to perform time-consuming operations. Other application components can start the service, and when the user switches to another scenario, the service will continue to run in the background. In addition, a component can be bound to a service interaction with it (IPC mechanism), for example, a service may handle network operations, play music, manipulate file I/O, or interact with content providers (provider), all of which are performed in the background.

"blog column:http://blog.csdn.net/column/details/alearning.html"

The service has two states, start and bind.

In the previous section we introduced the activity lifecycle, and in introducing service, we also need to introduce the concept of service life cycle.

The following is a life cycle diagram of the service:

Service Services:

       is a long life cycle, no user interface program, can be used to develop monitoring class programs. A good example is a media player that is playing songs from a playlist. In the application of a media player, there should be a lot of songsActivity, allowing users to select songs and play songs. However, the function of music replay does not correspond to theActivity, because the user will of course think that music should be played continuously while navigating to other screens. In this case, the media playerActivitywill useContext.startservice ()To start aService, so you can keep the music playing back in the background. At the same time, the system will also maintain thisServicebeen executed and know thisServiceRun end.In addition, we can also useContext.bindservice ()method to connect to aServiceon (If theServicedoes not run will start it). When connected to aServiceafter that, we can alsoServiceprovides an interface to communicate with it. Take the Media Player example, we can also pause, replay and other operations.

Service the use steps

1. Inherit Service class

2 , Androidmanifast.xml in the configuration manifest file <application> configuration of the service in the node

<span style= "FONT-SIZE:18PX;" ><!--Registered Service-        <service            android:name= " Cn.mahaochen.app.alearning.chapter5.TestService "            android:enabled=" true ">        </service></ Span>

service cannot run on its own , need to pass Contex.startservice () or Contex.bindservice () start the service.

       through startservice () The service initiated by the method is not related to the caller Even if the caller closes the service still running want to stop service to call Context.stopservice (), ondestory () , The service first starts the system by invoking the service's oncreate ()-->onstart ()

      If the service has started again, the call will only trigger the onstart () method. Use bindservice () Start the service with the caller binding The first time the service starts the system calls the service first. oncreate ()-->onbind (), If the service has started again, the call will no longer trigger this 2 methods When the caller exits, the system invokes the service's onunbind ( )-->ondestory () ;

want to actively unbind can be used Contex.unbindservice (), The system calls in turn Onunbind ()-->ondestory ( ) .

Test code: Testservice

Import Android.app.service;import android.content.intent;import Android.os.binder;import Android.os.IBinder;import Android.util.log;public class Testservice extends Service {//define tag tag private static final String tag = "Testservice";p Riva  Te mybinder mbinder = new Mybinder ();  @Overridepublic ibinder onbind (Intent Intent) {log.e (TAG, "Testservice start IBinder.");  return mbinder; return null;} @Overridepublic void OnCreate () {LOG.E (TAG, "Testservice start OnCreate."); Super.oncreate ();} @Overridepublic void OnStart (Intent Intent, int startid) {log.e (TAG, "Testservice start OnStart."); Super.onstart (Intent, Startid);} @Overridepublic void OnDestroy () {LOG.E (TAG, "Testservice start OnDestroy."); Super.ondestroy ();} @Overridepublic boolean onunbind (Intent Intent) {log.e (TAG, "Testservice start Onunbind."); return Super.onunbind (intent);} public class Mybinder extends Binder {public Testservice GetService () {return testservice.this;}}}

serviceactivity

Import Android.app.activity;import Android.content.componentname;import Android.content.serviceconnection;import Android.os.bundle;import Android.os.ibinder;import Android.view.view;import Android.view.View.OnClickListener; Import Android.widget.button;import Android.widget.toast;public class Serviceactivity extends Activity {private Testservice testservice;private Button Stopservicebutton; Stop Service button private button Bindservicebutton; Bind Service button Private button Unbindservicebutton; Unbind Service button//need to use serviceconnection in Context.bindservice and Context.unbindservice () to use private Serviceconnection mserviceconnection = new Serviceconnection () {@Overridepublic void onserviceconnected (componentname Name, IBinder service) {Testservice = ((testservice.mybinder) service). GetService (); @Overridepublic void onservicedisconnected (componentname name) {}} @Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate);//Set main layout file Xmlsetcontentview (r.layout.activity_Chapter5_service); Initviews ();} Initialize view private void Initviews () {Stopservicebutton = (Button) Findviewbyid (R.id.stopservice_button); Bindservicebutton = (Button) Findviewbyid (R.id.bindservice_button); Unbindservicebutton = (Button) Findviewbyid ( R.id.unbindservice_button); Srvactonclicklistener Clicklistener = new Srvactonclicklistener (); Stopservicebutton.setonclicklistener ( Clicklistener); Bindservicebutton.setonclicklistener (Clicklistener); Unbindservicebutton.setonclicklistener ( Clicklistener);} Internal classes, because this class only serviceactivity own use, so the internal class, but the interior of the use of the scene is not limited to this private class Srvactonclicklistener implements Onclicklistener {@Overridepublic void OnClick (View v) {switch (V.getid ()) {case R.id.stopservice_button:toast.maketext (Serviceactivity.this, "StopService", Toast.length_short). Show (); Break;case R.id.bindservice_button: Toast.maketext (Serviceactivity.this, "Bindservice", Toast.length_short). Show (); Break;case R.id.unbindservice_ Button:Toast.makeText (Serviceactivity.this, "Unbindservice", Toast.length_short). Show (); break;default:break;}}} 

Resources

1,http://blog.csdn.net/ryantang03/article/details/7770939

2,http://blog.csdn.net/android_tutor/article/details/5789203

"Alearning" chapter fifth introduction to Android related components (ii) Service

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.