1 Service 概述
Service 是没有用户界面,但它是在后台一只一直运行的,每个Service都继承类Service。与Activitvy及其他组件一样,Service同样运行在应用程序主线程中,所以不能阻塞其他进程的运行,通常需用对服务创建一个线程执行耗时的服务
2 Service生命周期
使用Service有两种方式:
一是使用Content上的StartService()的方法来启动一个线程;
另一种是使用bindservice()方法来绑定并启动一个线程。
和Activity相比 ,Service的生命周期会简单很多,使用stopservice()来关闭服务:其生命周期中相关的方法有以下三个:
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
}
同样和Activity一样来验证Service的启动和关闭服务的回调函数的调用情况,这里就不再验证了!比较简单!
在启动服务是首先调用onCreate(),再调用onStart(),服务开启;stopservice()时,调用ondestory()完成服务的关闭;
下面是简单的例子:

具体的代码如下:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:id="@+id/button1"
android:textColor="#ff0000"
android:layout_height="wrap_content"
android:text="启动服务"
android:onClick="start"
android:layout_width="wrap_content"></Button>
<Button
android:text="停止服务"
android:onClick="stop"
android:textColor="#00ff00"
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>
</LinearLayout>
ServiceActivity.java
public class ServiceActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void start(View view){
Intent intent = new Intent(this,service.class);
startService(intent);//开启服务
}
public void stop(View view){
Intent intent = new Intent(this,service.class);
startService(intent);//关闭服务
}
}
Service。java
/*在ononCreate()创建一个线程,开启线程
* 线程每隔一秒打印数值,可以再LOGCAT中看到
*/
public class service extends Service{
Boolean isRuning = true;
@Override
public IBinder onBind(Intent intent) {
//默认的都会有的不用管,可以看到返回值为null的
return null;
}
@Override
public void onCreate() {
Thread thread = new Thread(new mythread());
thread.start();
// thread.stop();目前是不建议使用的,使用可能会产生意想不到的后果
// 现在使用标志位isRuning控制
super.onCreate();
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
isRuning =false;
super.onDestroy();
}
class mythread implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
int i = 0;
while(isRuning){
System.out.println(i++);
try {
Thread.sleep(1000);//延迟
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
注意:必须在AndroidManifest.xml 注册服务<service android:name=".service"></service>;