本文共 1861 字,大约阅读时间需要 6 分钟。
继承关系
Context -> ContextWrapper -> Service 位于 android.app 包中
Service的生命周期
Service启动
1.StartService 同一个Service Start多次,onCreate()执行一次,onStartCommand()执行多次
2.BindService 同一个Service bind多次, onCreate()执行一次,onBind()也执行一次
注意:
1.启动也分隐式和显式.但考虑到安全等因数,如果不是也许需求 一般我们使用显示的调用方式。
2.onStartCommand(Intent intent, int flags, int startId)
onStartCommand有4种返回值
START_STICKY:如果service进程被kill掉,保留service的状态为开始状态,但不保留递送的intent对象。随后系统会尝试重新创建service,由于服务状态为开始状态,所以创建服务后一定会调用onStartCommand(Intent,int,int)方法。如果在此期间没有任何启动命令被传递到service,那么参数Intent将为null。
START_NOT_STICKY:“非粘性的”。使用这个返回值时,如果在执行完onStartCommand后,服务被异常kill掉,系统不会自动重启该服务。
START_REDELIVER_INTENT:重传Intent。使用这个返回值时,如果在执行完onStartCommand后,服务被异常kill掉,系统会自动重启该服务,并将Intent的值传入。
START_STICKY_COMPATIBILITY:START_STICKY的兼容版本,但不保证服务被kill后一定能重启。
3.BindService例代码
Service部分
private BindServiceX myBinderServiceX=new BindServiceX();
public class BindServiceX extends Binder{ public BindService getBindService() { return BindService.this;}}@Overridepublic IBinder onBind(Intent arg0) { // 此处返回自定义Binder return myBinderServiceX;}
组件调用部分(以Activity为例)
Intent intentBind = new Intent(AndroidServiceActivity.this, BindService.class);
bindService(intentBind,new ServiceConnection() {@Override public void onServiceDisconnected(ComponentName name) { } @Override public void onServiceConnected(ComponentName name, IBinder service) { //Service对外提供Bind BindServiceX bindServiceX = (BindServiceX) service; //通过bind提供的方法得到Service引用 BindService bindService = bindServiceX.getBindService(); //todo 接下来可以和Service通信了 }};
, Context.BIND_AUTO_CREATE);
Service关闭
1.stopSelf();
2.stopSelfResult();
3.stopService()
注意:
1.同时使用 startService 与 bindService 要注意到,Service 的终止,需要unbindService与stopService同时调用(调用顺序无所谓),才能终止 Service.
2.Service哪种方式启动必须调用与之对应方法才会关闭Service。
转载于:https://blog.51cto.com/4397014/2162424