Android Service Summary

Source: Internet
Author: User

1, through the StartService method to start a service, services can not start themselves. If you start an activity in a service, you must declare a new task for activity tasks. Services that are started by the StartService method do not die with the demise of the startup component, but instead continue to run.

Service life cycle onCreate ()-------->onstartcommand ()----------->ondestroy ()

StartService () When a service is started, it can cause the main thread to block if it takes a time-consuming operation and does not have a write thread!

The Onstartcommand () method runs continuously after the service starts running .

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 for the interface Description 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;} Defines the method that is called to the client (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 "> &lt ; USES-SDK android:minsdkversion= "8" android:targetsdkversion= "/> <application android:al" Lowbackup= "true" android:icon= "@drawable/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 add the Aidl package name to the class name--<action android:name= "com.example. Service. DataService "/> </intent-filter> </service> </application></manifest>

Client code:

To 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 allows for interprocess communication to be completed.


4. Use Bindservice to start the service and access the Local Service method.

Access 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; Defines a local Binder class that inherits Binderpublic class Localbinder extends binder{//gets the current instance of the Servie subclass to the client public MyService GetService () { return myservice.this;}} public int Getrandom () {return num.nextint (98);}}


This 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 to complete 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 know that it encapsulates the open thread), do not need to shut down the service, self-closing, single-threaded download data * * Must remember the instantiation!!! */public class Downloadservice extends Intentservice {@Overridepublic void OnCreate () {//TODO auto-generated method stubs Uper.oncreate ();} Public Downloadservice () {Super ("Downloadservice");} Simply copy the following method//Perform operation in the method @overrideprotected void Onhandleintent (Intent Intent) {//Get an instance of extracting network resources httpClient httpClient = new D EfaultHttpClient ()///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 {//Execute request get response HttpResponse HttpResponse = Httpclient.execute (HttpPost);//Judgment Response Status code if (httpres Ponse.getstatusline (). Getstatuscode () = = 200) {//Get response entity httpentity httpentity = httpresponse.getentity ();//Get Network data = Entityutils.tobytearray (httpentity);//Determine 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 Done", 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

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.