通过android的四大组件之一的service来实现后台运行,类似Windows上的服务。
1、Android上的service有两种启动方式(或者说两种方法实现service)
①startService()和bindService() ,有区别。
2、简单的使用Service步骤(startService()):
①建立service的子类,重写onStartCommand()。(当服务启动的时候会调用该方法)
| 
     1
     
     2
     
     3
     
     4
     
     5
     
     6
     
     7
     
     8
     
     9
     
     10
     
     11
     
     12
     
     13
     
     14
     
     15
     | publicclassHelloService extendsService {  @Override  publicvoidonCreate() {  }  //这个函数在低版本中使用的是onStart(),onStart()在高版本中已经过时了。  @Override  publicintonStartCommand(Intent intent, intflags, intstartId) {  } @Override  publicvoidonDestroy() {  }} | 
②在清单文件中声明Service组件
| 
     1
     
     2
     
     3
     
     4
     
     5
     
     6
     
     7
     | <application>           <serviceandroid:name="HelloService">                <intent-fiter>                    <actionandroid:name="xxxxx">                </intent-fiter>            </service></application> | 
③在Activity等调用startService(intent);启动你的Service
| 
     1
     
     2
     
     3
     | Intent intent = newIntent("xxxxx");//还可以使用Intent intent = new Intent(activity.this,HelloService.class);startService(intent); | 
注:两种方法各有不同,具体请看官方API:
http://developer.android.com/guide/components/services.html
原文:http://my.oschina.net/airship/blog/390620