本文章为读书笔记,书为《疯狂安卓讲义》。
1.Service的生命周期方法
1)IBinder onBind(Intent intent):该方法是Service子类必须实现的方法。该方法返回一个IBinder对象,应用程序可通过该对象与Service组件通信。
2)void onCreate():当该Service第一次被创建后将立即回调该方法。
3)void onDestroy():当该Service被关闭之前将会回调该方法。
4)void onStartCommand(Intent intent, int flags, int startId):该方法的早期版本是void onStart(Intent intent, int startId),每次客户端调用startService(Intent intent)方法启动该Service时都会回调该方法。
5)boolean onUnbind(Intent intent):当该Service上绑定的所有客户端都断开连接时将会回调该方法。
2.运行Service的两种方法
1)通过Context的startService()方法:通过该方法启用Service,访问者与Service之间没有关联,即使访问者退出了,Service仍然运行。
2)通过Context的bindService()方法:使用该方法启用Service,访问者与Service绑定在了一起,访问者一旦退出,Service也就终止。
3.Service与Activity通信
如果Activity想要访问Service的数据,那么久需要通过bindService()和unbindService()的方法来绑定、关闭Service。
bindService(Intent service, ServiceConnection conn, int flag):conn参数用于监听Activity与Service之间的连接情况。当Activity与Service成功连接之后将回调ServiceConnection对象中的onServiceConnected(ComponentName name, IBinder service)方法。
onServiceConnected()方法中的IBinder对象就是用于与Service之间的通信。在Service类中必须提供一个IBinder onBinder(Intent intent)方法,当Activity使用bindService()方法绑定Service时,onBinder()方法返回的IBinder类将传递给ServiceConnection对象中onServiceConnected(ComponentName name, IBinder service)方法的service参数,这样Activity既可通过IBinder对象获取Service的数据。.在实际开发中通常会采用集成Binder的方式来实现自己的IBinder对象。
4.Service的生命周期
用startService()方法启动Service时,Service的生命周期:onCreate()-->onStartCommand()(多次调用startService()方法时会被多次回调)-->onDestroy()
用bindService()方法启动Service时,Service的生命周期:onCreate()-->onBind()(多次调用bindService()方法时不会被多次回调)-->onUnbind()-->onDestory()
5.IntentService
Service本身存在的两个问题:
1)Service不会专门启动一条单独的进程,Service与它所在应用位于同一个进程中。
2)Service也不会专门一条新的进程,因此不应该在Service中直接处理耗时的任务。
IntentService的特征:
1)IntentService会创建单独的worker线程来处理所有的Intent请求。
2)IntentService会创建单独的worker线程来处理onHandlerIntent()方法实现的代码,因此开发者无须处理多线程问题。
3)当所有请求处理完成后,IntentService会自动停止,因此开发者无须调用stopSelf()方法来停止Service。
4)为Service的onBind()方法提供了默认实现,默认实现的onBind()方法返回null。
5)为Service的onStartCommand()方法提供了默认实现,该实现会将请求Intent添加到队列中。