First, Service introduction
Service is one of the four components of the Android system (activity, Service, Broadcastreceiver, ContentProvider), which is similar to the level of activity, but cannot run only in the background, And can interact with other components. Service can be used in many applications, such as multimedia playback when the user started other activity this time the program to continue to play in the background, such as the detection of changes in the file on the SD card, or in the background to record your geographic information changes, etc., in short, the service is always hidden in the background.
Service launches are available in two ways:Context.startservice () and Context.bindservice ()
Second, service START process
Context.startservice () Start process:
Context.startservice (), OnCreate (), OnStart (), Service running, Context.stopservice (), ondes Troy (), Service stop
If the service is not running, Android calls OnCreate () first and then calls OnStart ();
If the service is already running, only OnStart () is called, so a service's OnStart method may be called repeatedly.
If the stopservice will be directly OnDestroy, if the caller is directly exiting without calling StopService, the service will be running in the background, The service can be shut down by StopService after the caller has started up again.
so the life cycle of calling StartService is:onCreate -OnStart(can be called multiple times)--OnDestroy
Context.bindservice () Start process:
Context.bindservice (), OnCreate (), Onbind (), Service running, Onunbind (), OnDestroy ()- > Service Stop
Onbind () returns a Ibind interface instance to the client, Ibind a method that allows the client to callback the service, such as getting an instance of the services, running state, or other operations. This time the caller (context, for example, activity) is bound together with the service, the context exits, Srevice will call Onunbind->ondestroy exit accordingly.
So the lifetime of the call Bindservice is: onCreate---Onbind (one time, not multiple bindings)--onunbind--and ondestory.
only OnStart can be called multiple times (via multiple StartService calls) during each turn-off of the service, other Oncreate,onbind,onunbind, Ondestory can only be called once in a life cycle.
Third, service life cycle
Service life cycle is not as complex as activity, it only inherits OnCreate (), OnStart (), OnDestroy () three methods
When we first started the service, the OnCreate (), OnStart () methods were called, and the OnDestroy () method was executed when the service was stopped.
It is important to note that if the service is started, when we start the service again, the OnCreate () method is not executed, but the OnStart () method is executed directly.
It can stop itself through the service.stopself () method or the Service.stopselfresult () method, as long as the StopService () method is called to stop the service, regardless of how many times the startup service method is invoked.
Iv. Code Examples
(1)StartService Example
The project consists of two classes: Main Activity.java,playservice.java
Where:MainActivity. Java defines two buttons to control the playback and stop of the music, respectively.
Switch between activity and service with StartService and StopService, start service and cancel service, if not button, Service can be initiated and canceled in the activity's OnCreate and Ondestrpy
The Androidmanifest.xml file is as follows:
<manifest xmlns:android= "http://schemas.android.com/apk/res/android" package= " Com.example.serviceactivity " android:versioncode=" 1 " android:versionname=" 1.0 "> <uses-sdk android:minsdkversion= "8" android:targetsdkversion= "/>" <application android: Allowbackup= "true" android:icon= "@drawable/ic_launcher" android:label= "@string/app_name" android: Theme= "@style/apptheme" > <service android:enabled= "true" android:name= ". Playservice "/> </application> </manifest>
Layout layouts File Activity_main.xml
<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Android:paddi ngbottom= "@dimen/activity_vertical_margin" android:paddingleft= "@dimen/activity_horizontal_margin" Android: paddingright= "@dimen/activity_horizontal_margin" android:paddingtop= "@dimen/activity_vertical_margin" tools: Context= ". Mainactivity "> <button android:id=" @+id/button_on "android:layout_width=" Match_parent "and roid:layout_height= "Wrap_content" android:text= "open"/><button android:id= "@+id/button_off" an Droid:layout_width= "Match_parent" android:layout_height= "wrap_content" android:layout_below= "@id/button_on" android:text= "Close"/><textview android:id= "@+id/txt" android:layout_width= "Match_parent" a ndroid:layout_height= "Wrap_content" android:layout_below= "@id/button_off" android:text= "we'll via"/></relativelayout>
The Mainactivity.java code is as follows:
Package Com.example.hellowendy;import Android.app.activity;import Android.content.intent;import android.os.Bundle; Import Android.util.log;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;public class Mainactivity extends activity implements Onclicklistener {/** called when the activity is first created. */button Buttonon, Buttonoff; String TAG = "serviceactivity"; @Overridepublic void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (r.layout.activity_main); Buttonon = (Button) Findviewbyid (r.id.button_on); Buttonoff = (Button) Findviewbyid (R.id.button_off); Buttonon.setonclicklistener (this); Buttonoff.setonclicklistener (this); LOG.V (TAG, "activityoncreate");} @Overridepublic void OnClick (View v) {//TODO auto-generated method Stubswitch (V.getid ()) {case (r.id.button_on): LOG.V (T AG, "Activitystartservice"); This.startservice (New Intent (this, playservice.class));//StartService (new Intent (This, Playservice.class)); Break;case (R.id.button_off): {log.v (TAG, "Activitystopservice"); This.stopservice (New Intent (This, Playservice.class));//StopService (new Intent (this, playservice.class));} Break;default:break;}} @Overrideprotected void OnStop () {//TODO auto-generated method Stubsuper.onstop (); LOG.V (TAG, "Activityonstop");} @Overrideprotected void OnDestroy () {//TODO auto-generated method STUBLOG.V (TAG, "Activityondestroy"); Super.ondestroy ();}}
The Playservice.java code is as follows:
/** * *//** * @author Administrator * */package com.example.hellowendy;import java.io.ioexception;import android.app.Ser Vice;import Android.content.intent;import Android.media.mediaplayer;import Android.os.ibinder;import Android.util.log;import Android.widget.textview;import Android.widget.toast;public class PlayService extends Service {String TAG = "serviceactivity"; MediaPlayer MediaPlayer; @Overridepublic ibinder onbind (Intent Intent) {//TODO auto-generated method Stubreturn null;} @Overridepublic void OnCreate () {//TODO auto-generated method Stubsuper.oncreate (); Toast.maketext (This, "Play Service Created", Toast.length_long). Show (); LOG.V (TAG, "serviceoncreate");//textview Txtview;//txtview = (TextView) Findviewbyid (r.id.txt); <span style= " White-space:pre "></span>//song from local resources Cong.mp3," hurried that year ", <span style=" color: #ff0000; font-family: ' Black Verdana ', Arial, Helvetica, Sans-serif; font-size:14px; line-height:21px; " >cong.mp3 directory is Hellowendy-Res</span><span style= "font-family: ' Black Verdana ', Arial, Helvetica, Sans-serif; font-size:14px; line-height:21px; " ><span style= "color: #ff0000;" > ->raw -> Cong.mp3</span></span>mediaplayer = Mediaplayer.create (this, r.raw.cong) ;
} @Overridepublic void OnStart (Intent Intent, int startid) {//TODO auto-generated method Stub//super.onstart (Intent, star TID);//super.onstart ();/* *//You can create a link to the music in OnCreate, or create MediaPlayer = * Mediaplayer.create (this, in OnStart) R.raw.test); */toast.maketext (This, "Play Service OnStart", Toast.length_long). Show (); LOG.V (TAG, "Serviceonstart"); Mediaplayer.start ();} @Overridepublic void OnDestroy () {//TODO auto-generated method Stubsuper.ondestroy (); Toast.maketext (This, "Play Service Stopped", Toast.length_long). Show (); LOG.V (TAG, "Servicondestroy"); Mediaplayer.stop ();}}
Android Project Homehealth Basic Learning 1:service