Android Service详解
回调方法
- IBinder onBind(Intent i):该方法是Service子类必须实现的方法。返回一个IBinder对象,应用程序可以通过该方法与Service组件通信。
- void onCreate():在Service第一次被创建后立即回调。
- void onDestroy():在该Service被关闭前将回调该方法。
- void onStartCommand(Intent i,int flags,int startId):每次调用startService(Intent)方法启动Service时都会被回调。
- boolean onUnbind():当该Service上绑定的所有客户端都断开连接时会回调该方法。
启动与停止
- Context的startService()方法:通过该方法启动的Service,访问者与Service之间没有关联,即使访问者退出了,Service也仍然运行。
- Context的stopService()方法:使用该方法停止Service。
- Context的bindService()方法:使用该方法启动Service,访问者与Service绑定,访问者退出,Service终止。
- Context的unBindService()方法:使用该方法停止绑定Service。
PS: Android5.0以后,必须使用显式Intent启动Service组件。
绑定Service并通信
当程序通过startService()启动Service时,Service与访问者基本不存在关联,所以也无法进行通信与交换数据。
当访问者需要与Service进行方法调用,交换数据,应该使用bindService()与unbindService()方法启动关闭Service。
- bindService()方法的完整方法签名为:
bindService(Intent service,ServiceConnection conn, int flags) - service:启动的Service
- conn:ServiceConnection对象,返回启动Service的IBinder对象。
- flags:指定绑定时是否创建Service。如果为0不自动创建,或者BIND_AUTO_CREATE.
IBinder对象相当于Service组件内部的钩子,关联绑定到Service组件,当其他程序绑定该组件的Service时Service会将IBinder对象返回给其他程序的组件,通过Binder对象即可进行实时通信。
Service生命周期
- 多次调用startService()只会调用一次oncreate(),每次都会调用onStartCommand()
- 多次调用bindService()不会重复绑定只会调用一次onBind()
- 当Activity调用bindService()绑定一个已启动的Service时,只是将IBinder对象传给Activity,因此调用unBindService()只能解除绑定,并不能停止Service.
IntentService
IntentService是Service的子类,在Service的基础上增加额外的功能。
Service存在的问题
- 不会专门启动单独的进程,Service与其所在的应用位于同一进程。
- 不是一条新线程,不应该处理耗时的任务。
IntentService特征
- 创建单独的worker线程处理所有的Intent请求。
- 创建单独的worker线程处理onHandleIntent(),无须开发者处理多线程。
- 请求处理完成IntentService自动停止,无须调用stopSelf来停止该Service。
- onBind()提供默认实现,默认返回null。
- onStartCommand()方法提供默认实现,将Intent添加到队列中。
PS:扩展IntentService,无须重写onBind(),onStartCommand()方法,只需重写onHandleIntent()方法即可。
Moudle Demo代码
http://download.****.net/detail/demonliuhui/9831551
Demo里面囊括了bindService()绑定启动与startService()非绑定启动,与Activity进行数据通信,生命周期演示,
IntentService与普通的Service模拟耗时任务。
需要的可以自行下载测试。