2.service
(1)service通常位于后台运行,一般不与用于交互,故没有图形界面。
(2)service组件需要继承Service基类。
(3)service之间通过Intent而激活进行通信。
(4)必须要在AndroidManifest.xml配置文件中声明才能使用。
(5)和Activity一样,都是从Context派生出来的。
(6)两种启动模式:
(a)started(启动):当应用程序组件(如activity)调用startService()方法启动服务时,服务处于started状态。
步骤:
1.定义一个类继承Service
2.在AndroidManifest.xml文件中配置该Service
3.使用Context的startService(Intent)方法启动该Service
4.停止使用时,调用stopService(Intent)方法停止该服务
start方式启动的Service的生命周期如下:
onCreate()--->onStartCommand()(onStart()方法已过时) ---> onDestory()
(调用startService()) (stopService()或stopSelf())
说明:如果服务已经开启,不会重复的执行onCreate(), 而是会调用onStart()和onStartCommand()。服务停止的时候调用 onDestory()。服务只会被停止一次。(b)bound(绑定):当应用程序组件调用bindService()方法绑定到服务时,服务处于bound状态。
步骤:
1.定义一个类继承Service
2.在AndroidManifest.xml文件中配置该Service
3.使用Context的bindService(Intent, ServiceConnection, int)方法启动该Service
4.停止使用时,调用unbindService(ServiceConnection)方法停止该服务
bind方式启动的Service的生命周期如下:
onCreate() --->onBind()--->onunbind()--->onDestory()
(bindService())(unbindService())
注意:绑定服务不会调用onstart()或者onstartcommand()方法
区别
(1)当服务是started状态时,其生命周期与启动它的组件(开启者)无关,并且可以在后台无限期运行,即使启动服务的组件已经被销毁。开启者不能调用服务里面的方法。因此,服务需要在完成任务后调用stopSelf()方法停止,或者由其他组件调用stopService()方法停止。
(2)使用bindService()方法启用服务,调用者与服务绑定在了一起,调用者一旦退出,服务也就终止。
(7)service的关闭
对于通过startService()方法启动的服务要调用Context.stopService()方法关闭服务,使用bindService()方法启动的服务要调用Contex.unbindService()方法关闭服务。