android service两种启动方式

时间:2022-01-20 15:19:00

android service的启动方式有以下两种:

1、Context.startService()方式启动,生命周期如下所示,启动时,startService->onCreate()->onStart(),停止时,stopService->onDestroy(),如果调用者直接退出而没有停止Service,则Service会一直在后台运行;Context.startService()方法启动服务,在服务未被创建时,系统会先调用服务的onCreate()方法,接着调用onStart()方法。如果调用startService()方法前服务已经被创建,多次调用startService()方法并不会导致多次创建服务,但会导致多次调用onStart()方法;采用startService()方法启动的服务,只能调用Context.stopService()方法结束服务,服务结束时会调用onDestroy()方法。

android service两种启动方式

2、Context.bindService()方式启动,生命周期如下所示,绑定时,bindService -> onCreate() –> onBind(),调用者退出即解绑定时,Srevice就会unbindService –>onUnbind() –> onDestory(),一个Service可以同时和多个客户绑定,当多个客户都解除绑定之后,系统才会销毁service。

一个通过startService被开启的service有可能被绑定,这时,通过stopService()是不能停止这个服务的,只能将所有的绑定解除之后,才能停止服务。

android service两种启动方式