四大组件之Service
前言
Service 服务,即我们常指的“后台”,常用于一些不需要界面又需要长期运行的任务,例如后台下载、音乐播放。Service默认运行于主线程,因此若在Service执行一些耗时操作,可能会导致ANR,因此在执行耗时操作时常会开启一个子线程。常用的Service有IntentService,IntentService默认运行于子线程,且运行完后会自动销毁,适合一次性的任务
使用
Service 有两种开启方式:
- 启动服务
- 绑定服务
自定义一个服务
服务属于四大组件之一,在我们自定义Service时需要在Mainifest文件里面注册,当然,如果在File-new-Service 里面新建,AS会自动帮我们注册
启动服务
Intent intent = new Intent(this,MyService.Class); //MyService是自定义的服务
startService(intent);
停止服务
开启后服务会一直运行,直到在服务内调用了stopSelf() 或者在外部调用了stopService()
Intent intent = new Intent(this,MyService.Class); //MyService是自定义的服务
stopService(intent);
绑定服务
当我们需要与服务进行通信的时候,这时我们需要绑定一个服务。
Intent bindService = new Intent(this,MyService.class);
bindService(bindService,connection,BIND_AUTO_CREATE);
先看bindService方法:
@Override
public boolean bindService(Intent service, ServiceConnection conn,
int flags) {
return mBase.bindService(service, conn, flags);
}
我们需要传入三个参数:
- Intent 需要启动哪个服务
- ServiceConnection 当中包括两个回调
- flags 启动类型
@Override
public boolean bindService(Intent service, ServiceConnection conn,
int flags) {
return mBase.bindService(service, conn, flags);
}
ServiceConnection 对象
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
//获取在MyService里面 onBind方法返回的 Binder对象
//通过Binder对象可以与服务进行通信,
}
@Override
public void onServiceDisconnected(ComponentName name) {
//只有当 Service 被系统强制回收时调用
}
};
Flags:这里传入了
BIND_AUTO_CREATE 表示活动和服务进行绑定后会自动创建服务,此时会执行Service里面的 onCreate 但不会执行 onStartCommand();
关于onStartCommand()方法
- 多次调用startService()开启已存在的服务,不会多次执行onCreate 方法,但是会执行onStartCommand方法
- onStartCommand 可以有三种返回值关于服务保活:
START_NOT_STICKY
表示当Service运行的进程被Android系统强制杀掉之后,不会重新创建该Service。
START_STICKY
表示当Service运行的进程被Android系统强制杀掉之后,会重建Service,但是返回的Intent会为NULL
START_REDELIVER_INTENT
表示当Service运行的进程被Android系统强制杀掉之后,会重建Service,且返回的Intent会为最后一次传入onStartConmmand的Intent
服务的生命周期
先放一张经典的服务生命周记图
接下来对服务的生命周期进行测试:
一 、正常 startService、stopService 调用
二 、 先开启,再绑定,先解绑,再停止 :
startService - bindService - unbindService - stopService
startService启动的服务绑定后需要使用stopService才能停止 解绑不进入onDestroy方法
三、先开启,在绑定,先停止,再解绑 :
先开启,再绑定的服务,直接停止服务不会调用onDestroy,而解绑后会直接进入onDestroy
四、绑定服务:
绑定不会开启服务,但是会调用 ServiceConnection 中的 onServiceConnected 方法 并且已绑定时再次绑定是没有效果的
五、绑定后的两种顺序停止顺序:
- bind – start – stop – unbind
此时点击stop 服务仍然存在 再点击 unbind时 会直接销毁 - bind – start – unbind – stop
先解绑并不会销毁服务,解绑后停止服务时会销毁
小结:
onUnbind 总是在 onDestroy 之前 如果在调用了stopService时,存在 绑定,在解绑时会同时销毁
调用了stopService 在无绑定的情况下就会直接进入onDestroy
多个活动绑定同个服务
获取到的binder对象是同一个