Android service Summary
1. Start a service using the startservice method. The service cannot start itself. If you start an activity in a service, you must declare a brand new activity TASK. Services started using the startservice method will not die as the startup components die, but will continue to run.
Service Life Cycle onCreate () --------> onStartCommand () -----------> onDestroy ()
After startService () starts a service, if it is time-consuming and has no write thread, it will cause the main thread to block!
The onStartCommand () method is always run after the service is started.
2. Start a service with bindService. The service and activity are bound together: at startup, onCreate () ------> onBind () ---------> onServiceConnected (), the component of the startup service is extinct, and the service is also extinct.
3. AIDL service call Method
Demo: http://download.csdn.net/detail/u014600432/8175529
1) server code:
First, define an Interface Description Language Interface:
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 extends Service {@ Overridepublic IBinder onBind (Intent arg0) {// return the binder generated by the didl file ;} // define the method called by the client (aidl file) Binder binder = new DataService. stub () {@ Overridepublic double getData (String arg) throws RemoteException {if (arg = "a") {return 1 ;}if (arg = "B ") {return 2 ;}return 0 ;}};}
Server list file:
Client code:
Copy the aidl 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; // defines an 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 the service btn1.setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {Intent intent Intent = new Intent (DataService. class. getName (); // start the service bindService (intent, conn, BIND_AUTO_CREATE) ;}}); // call the 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-to-service interaction private ServiceConnection conn = new ServiceConnection () {@ Overridepublic void onServiceDisconnected (ComponentName name) {}@ Overridepublic void onServiceConnected (ComponentName, IBinder service) {// input servicedataService = DataService. stub. asInterface (service) ;}}; @ Overridepublic boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater (). inflate (R. menu. main, menu); return true ;}}
In this way, inter-process communication can be completed.
4. Use bindService to start the service and access the local service.
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) {// 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; // 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 the service method btnCall. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {// if (flag) {int result = myService. getRandom (); TV. setText ("<+ result) ;}});} private ServiceConnection serviceConnection = new ServiceConnection () {// connection @ Overridepublic void onServiceConnected (ComponentName arg0, IBinder iBinder) {// obtain The IBinder of the Service's communication channel, which you can now make CILS on. localBinder binder = (LocalBinder) iBinder; // obtain the service myService = binder. getService (); flag = true;} // not connected @ Overridepublic void onServiceDisconnected (ComponentName arg0) {flag = false ;}; @ Overridepublic boolean onCreateOptionsMenu (Menu menu Menu) {// Inflate the menu; this adds items to the action bar if it is present. 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 (); private final Random num = new Random (); @ Overridepublic IBinder onBind (Intent arg0) {// return the return lb of the subclass instance of the local Binder ;} // define a local Binder class that inherits the Binderpublic class LocalBinder extends Binder {// obtain the current instance of the Servie subclass to the client public MyService getService () {return MyService. this ;}} public int getRandom () {return num. nextInt (98 );}}
You can use this demo to access the methods in the local service.
Demo: http://download.csdn.net/detail/u014600432/8175633
5. IntentService
In essence, it is to start a thread to complete time-consuming operations.
IntentService lifecycle:
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. I Mpl. 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 does not need to enable the thread (see the source code that encapsulates the enabled thread). You do not need to disable the service and close it yourself, download data from a single thread ** be sure to instantiate it !!! */Public class DownLoadService extends IntentService {@ Overridepublic void onCreate () {// TODO Auto-generated method stubsuper. onCreate () ;}public DownLoadService () {super ("DownLoadService") ;}// you only need to rewrite the following method // execute the operation in this method @ Overrideprotected void onHandleIntent (Intent intent) {// obtain the instance HttpClient httpClient = new DefaultHttpClient () for extracting network resources; // sets the Request Method HttpPost httpPost = new HttpPost (intent. getStringExtra ("url" ); // Set the storage path File = new file (Environment. getExternalStorageDirectory (), "IntentService.gif"); // defines the output stream used to write FileOutputStream fileOutputStream = null; byte [] data = null; // Network Data try {// execute the request to obtain the response HttpResponse httpResponse = httpClient.exe cute (httpPost); // determine the response status code if (httpResponse. getStatusLine (). getStatusCode () = 200) {// get the response entity HttpEntity httpEntity = httpResponse. getEntity (); // obtain Network data = EntityUtils. ToByteArray (httpEntity); // determines whether the SD card is available if (Environment. getExternalStorageState (). equals (Environment. MEDIA_MOUNTED) {// write the SD card fileOutputStream = new FileOutputStream (file); fileOutputStream. write (data, 0, data. length); // Toast. makeText (DownLoadService. this, "download completed", Toast. LENGTH_LONG ). show (); Toast. makeText (getApplicationContext (), "download completed", 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 catch blocke. printStackTrace ();}}}}}
Call 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 present.getMenuInflater().inflate(R.menu.main, menu);return true;}}
Demo: http://download.csdn.net/detail/u014600432/8175673