I. Introduction of ANDROID Services
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 ()
II. Principles and processes
1. Create a foreground service, just provide a notification bar icon and call Startforeground.
2. Want to let the service do their own things to do, but also relatively simple, just need to oncreate or Onstartconmand when the new one thread can be
3. What if the UI, such as activity, wants to communicate with the service and invoke the methods provided by the service? You need to use the binder at this time: only need to return a IBinder object when Onbind, through which can get the object reference of the current service, so as to operate the method provided by the service, how to acitivty in the services operation?
With the service reference, this time only needs to open the callback interface to the activity in the service.
4. Of course, the service needs to be configured in the Manifest.xml declaration:
<service android:name= "Com.czm.servicetest.MyService" > </service>
Third, example: Myservice.java
Packagecom.czm.servicetest;ImportAndroid.app.Service;Importandroid.content.Intent;ImportAndroid.os.Binder;ImportAndroid.os.IBinder;ImportAndroid.util.Log;/*** The Service Example *@authorcaizhiming **/ Public classMyServiceextendsservice{IBinder Mbinder=NewMybinder (); Private intMCount = 0; Public BooleanMisstop =false; //get the instance of MyService Public classMybinderextendsbinder{MyService GetService () {returnMyService. This; } } Public voidSetData (intdata) {MCount=data; } Public intGetData () {returnMCount; } @Override Public voidonCreate () {//TODO auto-generated Method Stub Super. OnCreate (); Thread Thread=NewThread (NULL,NewServiceworker (), "Serviceworker"); Thread.Start (); } @Override Publicibinder onbind (Intent Intent) {//TODO auto-generated Method StubLOG.V ("Czm", "Onbind ()-service is started"); returnMbinder; } @Override Public intOnstartcommand (Intent Intent,intFlagsintStartid) { //TODO auto-generated Method StubLOG.V ("Czm", "Onstartcommand ()-service is started"); return Super. Onstartcommand (Intent, flags, Startid); } //The Service work ' s thread classServiceworkerImplementsrunnable{@Override Public voidrun () {//TODO auto-generated Method Stub while(!misstop) {LOG.V ("Czm", "serviceworker:mcount=" +mCount); MCount++; if(MCount >= 10000) {MCount= 0; } if(mCount%5 = = 0) {mlistener.oncallback (); } Try{Thread.Sleep (1000); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } } } } //The callback listener to operate UI such as Activity PrivateOnuicallbacklistener Mlistener; Public voidSetlistener (Onuicallbacklistener listener) {Mlistener=Listener; } Public Interfaceonuicallbacklistener{voidOnCallback (); } }
Iv. How to use the service-myservice?
Packagecom.czm.servicetest;ImportCom.czm.servicetest.MyService.MyBinder;ImportCom.czm.servicetest.MyService.OnUICallbackListener;Importandroid.app.Activity;ImportAndroid.content.ComponentName;Importandroid.content.Intent;Importandroid.content.ServiceConnection;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.os.IBinder;ImportAndroid.os.Message;ImportAndroid.util.Log;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button;ImportAndroid.widget.TextView;ImportAndroid.widget.Toast; Public classMainactivityextendsActivityImplementsonuicallbacklistener{PrivateButton Mbtnstart; PrivateButton Mbtnchange; PrivateButton Mbtnstop; PrivateTextView Mtvresult; PrivateMyService Mmyservice; Intent serviceintent; PrivateHandler Mhandler =NewHandler () { Public voidhandlemessage (Message msg) {Mtvresult.settext (string.valueof (Mmyservice.getdata ())); Mhandler.sendemptymessagedelayed (0, 1000); }; }; PrivateServiceconnection mserviceconnection =Newserviceconnection () {@Override Public voidonservicedisconnected (componentname name) {//TODO auto-generated Method StubLOG.V ("Czm", "onservicedisconnected ()"); } @Override Public voidonserviceconnected (componentname name, IBinder service) {//TODO auto-generated Method StubLOG.V ("Czm", "onserviceconnected ()"); Mybinder Binder=(mybinder) service; Mmyservice=Binder.getservice (); Mmyservice.setlistener (mainactivity. This); Mhandler.sendemptymessagedelayed (0, 0); } }; @Overrideprotected voidonCreate (Bundle savedinstancestate) {//TODO auto-generated Method Stub Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); Mbtnstart=(Button) Findviewbyid (R.id.btn_start); Mbtnchange=(Button) Findviewbyid (R.id.btn_change); Mbtnstop=(Button) Findviewbyid (r.id.btn_stop); Mtvresult=(TextView) Findviewbyid (R.id.tv_result); Mbtnstart.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View arg0) {//TODO auto-generated Method Stub//Start ServiceServiceintent =NewIntent (mainactivity. This, MyService.class); Serviceintent.addflags (Intent.flag_activity_new_task); //bind service in order to communicate with serviceMainactivity. This. Bindservice (Serviceintent, mserviceconnection, bind_auto_create);//StartService (serviceintent); } }); Mbtnchange.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View arg0) {//TODO auto-generated Method StubMmyservice.setdata (1000); } }); Mbtnstop.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View arg0) {//TODO auto-generated Method StubMmyservice.misstop =true; Mainactivity. This. Unbindservice (mserviceconnection); StopService (serviceintent); } }); } /*** Service Callback *@paramserviceconnection*/@Override Public voidOnCallback () {//TODO auto-generated Method StubRunonuithread (NewRunnable () {@Override Public voidrun () {//TODO auto-generated Method StubToast.maketext (mainactivity. This, "Service Callback", Toast.length_short). Show (); } }); }}
Android Four components service-service