1, start a service through the StartService method. The service cannot start itself. If you start an activity in a service, you must declare a new task for activity tasks. Services started by the StartService method do not die with the demise of the startup component, but are always executed.
Service life cycle onCreate ()-------->onstartcommand ()----------->ondestroy ()
StartService () after starting a service. If the service takes a time-consuming operation and there is no write thread, it will cause the main thread to clog!
The Onstartcommand () method is always executed after the service starts executing .
2, start a service with Bindservice, the service and activity are bound together: when starting, call onCreate ()------> Onbind ()--------->onserviceconnected (), the component that started the service dies, and the service dies.
3. AIDL Service Invocation Mode
demo:http://download.csdn.net/detail/u014600432/8175529
1) service-side code:
First define an interface to describe the interface of the narrative language:
Package Com.example.service;interface dataservice{double getData (String arg);}
Then define the service component code:
/** *version: *author:yangquanqing *data: */package com.example.android_aidl_service;import Com.example.service.dataservice;import Android.app.service;import Android.content.intent;import Android.os.Binder Import Android.os.ibinder;import android.os.remoteexception;/** * @author yangquanqing yqq * */public class MyService ex Tends Service {@Overridepublic ibinder onbind (Intent arg0) {<span style= "color: #ff0000;" >//return binder generated by the Didl file </span>return binder;} Method defined for client invocation (aidl file) Binder binder=new <span style= "color: #ff0000;" >dataservice.stub () </span> {@Overridepublic double getData (String arg) throws RemoteException {if (arg== "a") { return 1;} if (arg== "B") {return 2;} return 0;}};}
Server-side manifest file:
<?xml version= "1.0" encoding= "Utf-8"?><manifest xmlns:android= "http://schemas.android.com/apk/res/android" package= "Com.example.android_aidl_ Service "android:versioncode=" 1 "android:versionname=" 1.0 "> <uses-sdk android:minsdkversion=" 8 " android:targetsdkversion= "/> <application android:allowbackup=" true "android:icon=" @drawabl E/ic_launcher "android:label=" @string/app_name "android:theme=" @style/apptheme "> <activity Android:name= "Com.example.android_aidl_service. Mainactivity "android:label=" @string/app_name "> <intent-filter> <action Android:name= "Android.intent.action.MAIN"/> <category android:name= "Android.intent.category.LAUNCHER "/> </intent-filter> </activity> <service android:name=" Com.exampl E.android_aidl_service. MyService "> <intent-filter> ≪! --Intent filter to put AIDL package name plus class name--<action android:name= "Com.example.service.DataService"/> </i Ntent-filter> </service> </application></manifest>
Client code:
Copy the Aidl file package to the client. The client code is as follows:
Package Com.example.android_aidl_client;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.os.remoteexception;import Android.view.menu;import Android.view.View;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.textview;import Com.example.service.dataservice;public class Mainactivity extends Activity {private Button btn1,btn2;// Define a Aidl instance private DataService dataservice;private TextView TV; @Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); btn1= (Button) This.findviewbyid (R.id.button1); btn2= (Button) This.findviewbyid (R.id.button2); tv= (TextView) This.findviewbyid ( R.ID.TEXTVIEW1);//Bind service Btn1.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View v) {Intent Intent=new Intent (DataService.class.getName ());//Start Service Bindservice (Intent, Conn, bind_auto_create);}); /Invoke Service method Btn2.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View v) {try {int result= (int) Dataservice.getdata ("a"); Tv.settext (result+ "");} catch (RemoteException e) {//TODO auto-generated catch Blocke.printstacktrace ();}});} Client interacts with service private serviceconnection conn=new serviceconnection () {@Overridepublic void onservicedisconnected ( ComponentName name) {} @Overridepublic void onserviceconnected (componentname name, IBinder service) {// Incoming servicedataservice=dataservice.stub.asinterface (service);}; @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it is PR Esent.getmenuinflater (). Inflate (R.menu.main, menu); return true;}}
This will allow the interprocess communication to complete.
4. Start the service with Bindservice and visit the Local service method.
To access the interface code:
Package Com.example.android_service_binder;import Android.app.activity;import Android.content.ComponentName; Import Android.content.context;import Android.content.intent;import Android.content.serviceconnection;import Android.os.bundle;import Android.os.ibinder;import Android.view.menu;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.textview;import Com.example.android_service_binder. Myservice.localbinder;public class Mainactivity extends Activity {//Destroy binding @overrideprotected void OnStop () {Super.onstop (); if (flag) {//Unbind Unbindservice (serviceconnection); flag=false;}} Bind service@overrideprotected void OnStart () {//TODO auto-generated method Stubsuper.onstart ();/*intent intent=new Intent (Mainactivity.this,myservice.class);//Start Servicebindservice (Intent, Serviceconnection, context.bind_auto_ CREATE); */}private button btnbinder=null;private button btncall=null;private TextView tv=null;private myservice Myservice;//service instance PrivaTe boolean flag=false;//is not bound by default @overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (R.layout.activity_main); btnbinder= (Button) This.findviewbyid (R.id.button1); Btncall= (Button) This.findviewbyid (R.id.button2); tv= (TextView) This.findviewbyid (R.ID.TEXTVIEW1); Btnbinder.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {Intent intent=new Intent ( Mainactivity.this,myservice.class);//Start Servicebindservice (Intent, serviceconnection, context.bind_auto_create);}); /Call service method Btncall.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View v) {//In bind state if (flag) {int result=myservice.getrandom (); Tv.settext ("<<<<<" +result);}});} Private serviceconnection serviceconnection= New Serviceconnection () {//connection @overridepublic void onserviceconnected ( ComponentName arg0, IBinder ibinder) {//Get services for the ibinder of the service ' s communication channel, which you can now make CA LLS on. Localbinder binder= (Localbinder) ibinder;//Get Service Myservice=binder.getservice (); flag=true;} Do not connect @overridepublic void onservicedisconnected (ComponentName arg0) {flag=false;}}; @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it is PR Esent.getmenuinflater (). Inflate (R.menu.main, menu); return true;}}
Service Component code:
/** *version: *author:yangquanqing *data: */package com.example.android_service_binder;import java.util.Random; Import Android.app.service;import android.content.intent;import android.os.binder;import android.os.IBinder;/** * @ Author Yangquanqing yqq * */public class MyService extends Service {private final Localbinder lb=new Localbinder ();p rivate Final random num=new random (); @Overridepublic ibinder Onbind (Intent arg0) {//Returns a subclass instance of local binder return lb; Define a local Binder class to inherit Binderpublic class Localbinder extends binder{//get Servie subclass current instance to clientpublic MyService GetService () { return myservice.this;}} public int Getrandom () {return num.nextint (98);}}
The demo allows you to access the methods inside the local service.
demo:http://download.csdn.net/detail/u014600432/8175633
5,Intentservice
The essence is to open a thread and finish the time-consuming operation.
Intentservice life cycle :
OnCreate ()------->onstartcommand ()--------->onhandleintent ()--------->ondestroy ()
/** *version: *author:yangquanqing *data: */package com.example.android_intentservice;import Java.io.File;import Java.io.fileoutputstream;import Java.io.ioexception;import Org.apache.http.httpentity;import Org.apache.http.httpresponse;import Org.apache.http.client.clientprotocolexception;import Org.apache.http.client.httpclient;import Org.apache.http.client.methods.httppost;import Org.apache.http.impl.client.defaulthttpclient;import Org.apache.http.util.entityutils;import Android.app.intentservice;import Android.content.intent;import Android.os.environment;import Android.widget.Toast ;/** * @author yangquanqing do not need to open the thread (see the source code know that it encapsulates the open thread), do not need to shut down the service, self-closing, single-threaded download data * * Must remember to instantiate!!
!
*/public class Downloadservice extends Intentservice {@Overridepublic void OnCreate () {//TODO auto-generated method stub Super.oncreate ();} Public Downloadservice () {Super ("Downloadservice");} Only need to replicate such as the following method//run operation in this method @overrideprotected void Onhandleintent (Intent Intent) {//Get an instance of extracting network resources httpClient HttpClient = New Defaulthttpclient ()///Set request mode HttpPost HttpPost = new HttpPost (Intent.getstringextra ("url"));//Set storage path File File = new File (Environment.getexternalstoragedirectory (), "intentservice.gif");//define output stream for write FileOutputStream FileOutputStream = null;byte[] data = null;//Network data try {//Run request get response HttpResponse HttpResponse = Httpclient.execute (HttpPost);//inferred Response status code if (HT Tpresponse.getstatusline (). Getstatuscode () = = 200) {//Get response entity httpentity httpentity = httpresponse.getentity ();// Obtain Network data = Entityutils.tobytearray (httpentity);//Infer if the SD card is available if (Environment.getexternalstoragestate (). Equals ( environment.media_mounted)) {//write SD card fileoutputstream=new fileoutputstream (file); Fileoutputstream.write (data,0, Data.length);//toast.maketext (downloadservice.this, "Download Complete", Toast.length_long). Show (); Toast.maketext (Getapplicationcontext (), "Download Complete", Toast.length_long). Show ();}} catch (Clientprotocolexception e) {//Todo auto-generated catch Blocke.printstacktrace ();} catch (IOException e) {//TODO Auto-generated catch Blocke.printstacktrace ();} finally {if (FileOutputStream! = null) {try {fileoutputstream.close ()} catch (IOException e) {//TODO auto-generated CATC H Blocke.printstacktrace ();}}}}
Invoke the Service interface:
package com.example.android_intentservice;import Android.app.activity;import Android.content.intent;import Android.os.bundle;import Android.view.menu;import Android.view.View;import Android.view.view.onclicklistener;import Android.widget.button;public class Mainactivity extends Activity {private Button btn_intent=null;private String url= "http://www.baidu.com/img/bdlogo.gif"; @Overrideprotected void OnCreate ( Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); btn_intent = (Button) This.findviewbyid (R.id.button1); Btn_intent.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View arg0) {Intent intent=new Intent (mainactivity.this,downloadservice.class); Intent.putextra ("url", URL); StartService (intent);}}); @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it is PR Esent.getmenuinflater (). Inflate (R.menu.main, menu); return true;}}
demo:http://download.csdn.net/detail/u014600432/8175673
Android Service Summary