Service 是Android系统中类型于Activity 的一种组件,不能自己启动,也不能与用户交互,只能运行于后台。
Service和Activity一样,拥有自己的生命周期,其分别为onCreate()、onStart()、onDestory()方法,生命周期开始于onCreate()方法而止于onDestory()方法
Service分为以下两种类型:1、本地服务:用于程序内部 2、远程服务:用于Android系统内部的各应用程序之间
前者用于实现应用程序自己的一些耗时任务,后者可被其他应用程序应用程序复用
实现Service需要继承Service类,其启动方式有两种:startService()和bindService(),相应的结束方式分别为:stopService()和unbindService()
startService()方法启动服务,调用者与服务之间没有关联,即使调用者退出了,服务任然运行
bindService()方法启动服务,调用者与服务绑定在一起,调用者一旦退出了,服务也就终止了
serveice 的使用方法如下:使用之前记得必须在
AndroidMainfest.xml 中注册该 service ,就像注册 Acitivty 一样
新建一个java文件定义services类:将要实现的后台服务功能写在这个类里面即可
/Service 类
package com.example.android_test;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class CountService extends Service{
private boolean threadable = true;
private int count;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
while(threadable)
{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
count ++;
Log.v("test", "count is:"+count);
}
}
}).start();
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
//结束进程
threadable = false;
}
}
在主java文件中开启和关闭services:
//开启服务
Intent intent = new Intent(MainActivity.this,CountService.class);
startService(intent);
//关闭服务
Intent intent = new Intent(MainActivity.this,CountService.class);
stopService(intent);