Android Service 简单介绍

Service 的生命周期,两种启动方式的区别

答案参考自:

Service 生命周期

使用context.startService 启动Service

其生命周期为 context.startService() -> onCreate()- > onStartCommand()-> Service running -> context.stopService() | -> onDestroy() -> Service stop

  1. 如果Service还没有运行,则Android先调用onCreate()然后调用onStart();
  2. 如果Service已经运行,则只调用onStartCommand(),所以一个ServiceonStartCommand方法可能会重复调用多次。

stopService的时候直接onDestroy,如果是调用者自己直接退出而没有调用stopService的话,Service会一直在后台运行。该Service的调用者再启动起来后可以通过stopService关闭Service

**所以调用startService的生命周期为:onCreate –> onStartCommand(可多次调用) –> onDestroy**。

对于bindService启动Service会经历:

context.bindService() -> onCreate()-> onBind() ->Service running -> onUnbind() -> onDestroy() -> Service stop

onBind将返回给客户端一个IBind接口实例,IBind允许客户端回调服务的方法,比如得到Service运行的状态或其他操作。

这个时候把调用者(Context,例如Activity)会和Service绑定在一起,Context退出了,Srevice就会调用onUnbind -> onDestroy相应退出。

所以调用bindService的生命周期为:onCreate –> onBind(只一次,不可多次绑定) –> onUnbind –> onDestory

一但销毁activity它就结束,如果按home把它放到后台,那他就不退出。

补充

在 Service 每一次的开启关闭过程中,只有onStartCommand可被多次调用(通过多次startService调用),
其他onCreateonBindonUnbindonDestory在一个生命周期中只能被调用一次。


Android Service 简单介绍
https://luoyuy.top/posts/60d6ebb66cb6/
作者
LuoYu-Ying
发布于
2022年5月24日
许可协议