前言:
服务是android中实现程序后台运行的解决方案,非常适合去执行那些不需要和用户交互而且还要求长期运行的任务。
服务的运行期不依赖于任何用户界面,即使被程序切换到了后台,或者启动了另外一个进程,服务依然保持正常运行。
1,服务所在进程依赖于创建服务的进程,当一个进程被杀掉时,所有依赖于该进程的服务所在进程也会停止运行。
2,服务中的代码默认在主线程中执行,如果有耗时操作,必须手动开启并且在子线程中执行。
1,生命周期
启动的服务的生命周期:
1,如果一个Service被startService 方法多次启动,那么onCreate方法只会调用一次,onStartCommand将会被调用
多次(对应调用startService的次数);
2,系统只会创建Service的一个实例(因此你应该知道只需要一次stopService调用);
3,Service将会一直在后台运行,直到被调用stopService,或自身的stopSelf方法。当然如果系统资源不足,
android系统也可能结束服务。
绑定的服务的生命周期:
1,如果一个Service被Activity 调用 Context.bindService 方法绑定启动,不管调用 bindService 调用几次,onCreate方法
都只会调用一次,同时onBind方法被多次调用;
2,当连接建立之后,Service将会一直运行,除非调用Context.unbindService 断开连接或者之前调用bindService 的
Context 不存在了(如Activity被finish的时候),系统将会自动停止Service,对应onDestroy将被调用。
启动又被绑定的服务的生命周期:
1,如果一个Service又被启动又被绑定,则该Service将会一直在后台运行。并且不管如何调用,onCreate始终只会调用
一次,对应startService调用多少次,Service的onStartCommand便会调用多少次。
2,调用unbindService将不会停止Service,而必须调用 stopService 或 Service的 stopSelf 来停止服务。
停止服务:
当一个Service被终止(1、调用stopService;2、调用stopSelf;3、不再有绑定的连接(没有被启动))时,
onDestroy方法将会被调用。
当然,在开发中,绑定服务进行跨进程通信的实例比较多。
2 Service 与 Thread 的区别
首先
Thread 是程序执行的最小单元,它是分配CPU的基本单位。可以用 Thread 来执行一些异步的操作。
Service是Android的四大组件之一,被用来执行长时间的后台任务。默认情况下Service是运行在主线程中的。
当然区别有很多,其中2点如下:
1.在android中,Thread只是一个用来执行后台任务的工具类,它可以在Activity中被创建,也可以在Service中被创建。
2.Service组件主要有两个作用:后台运行和跨进程访问。service可以在android系统后台独立运行,线程是不可以的。
3IntentService
一般的service有时候需要手动创建子线程,手动控制其生命周期,但是IntentService将这些都实现好了, 当所有的任务完成
的时候,会自己退出。
使用IntentService其实很简单, IntentService是一个抽象类,有一个抽象的onHandleIntent方法。因此,继承IntentService并且
实现构造方法和onHandleIntent方法就可以了。
IntentService源码如下,
public abstract class IntentService extends Service {
private volatile Looper mServiceLooper;
private volatile ServiceHandler mServiceHandler;
private String mName;
private boolean mRedelivery;
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
onHandleIntent((Intent)msg.obj);
stopSelf(msg.arg1);
}
}
public IntentService(String name) {
super();
mName = name;
}
public void setIntentRedelivery(boolean enabled) {
mRedelivery = enabled;
}
@Override
public void onCreate() {
super.onCreate();
HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
@Override
public void onStart(Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
onStart(intent, startId);
return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}
@Override
public void onDestroy() {
mServiceLooper.quit();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@WorkerThread
protected abstract void onHandleIntent(Intent intent);
主要是利用HandlerThread来实现的。执行完成onHandleIntent方法之后,就会调用stopSelf终止服务。