1.Service生命周期
2.不同情况下生命周期情况
-
startService/stopServie 生命周期顺序:onCreate -> onStartCommand ->onDestroy
- 第一次调用startService会触发onCreate和onStartCommand,以后在服务进行过程中,每次调用startService都只会触发onCreateStartCommand。
- 不论startService次,stopService一次就能停止服务。
-
bindService/unbindServie 生命周期顺序:onCreate -> onBind -> onUnBind -> onDestroy 该方法启动的服务,不论bindService调用多少次,onCeate方法只能启动一次,同时onStartCommond 方法始终不会调用。伴随启动它的Context,如果context结束了,service也会结束。
- 第一次bindService会触发onCreate和onBind,以后的服务运行过程中,每次bindService都不会触发任何回调。
-
混合型(上面两种方式的交互) 当一个Service在被启动(startService)的同时又被绑定(bindService),该Service将会一直在后台运行,并且不管调用几次,onCreate方法只会被调用一次,onStartCommand的次数和startService次数一致(使用bindService不会调用onStartCommand)。同时调用unBindService方法将不会停止Service,必须调用onStopService或Service自身的stopSelf来停止。
-
什么时候使用startService或者bindService或者同时使用startService和bindService
- a.如果只是想要一个后台服务长期进行某项任务那么使用startService便可以了。
- b.如果想要与正在运行的Service进行联系。1.使用broadcast进行通信,如果通信比较频繁,容易造成性能上的问题,BroadcastReciver本身执行代码的时间很短,搞不好执行到一半不执行了。2.使用bindService,没有上述问题(这个时候,startService和bindService就已经同时在使用了)。
- c.如果服务只是公开一个远程接口,提供接上的服务端(Android的Service是C/S结构)远程调用执行方法。这个时候,可以不比立即启动Service,而只用BindService,这样在第一次bindService的时候才会创建服务的实例。
3.Service的几种典型使用实例
- 不可交互的后台服务 普通的Service,通过startService()方式开启。Service的生命周期:onCreate ->onStartCommand -> onDestroy。
public class BackService extends Service {
private Thread mThread;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mThread = new Thread() { //执行耗时操作
@Override
public void run() {
try {
while (true) {
if (this.isInterrupted()) {//等待线程停止
throw new InterruptedException();
}
System.out.println("执行耗时操作");
}
} catch (Exception exception) {
}
}
};
mThread.start();
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
mThread.interrupt(); //停止线程
}
}