主要说明Started Service与Bound Service的区别于联系。
一:基本用法
Stared Service
对于一个Component
对象,调用startService(Intent aIntent)
来启动一个Service
。
启动之后,在Service
里面onStartCommand(Intent intent,int flags,int startId)
方法里面的Intent
就是startService(Intent aIntent)
传入的aIntent
对象(startId
参数的说明:因为一个Service
可能处理多个request,所以多次调用startService()
就会产生一个startId
,并且是从1开始的。。。。原文如下:you handle each call to onStartCommand()
yourself, you can perform multiple requests simultaneously,flags
参数的说明:暂时还没搞懂)
Started Service
由于是一直在运行,像音乐播放器,可以用前台服务(Service in the Foreground)调用startForeground(int id, Notification notification)
即可,System一般在内存不足的时候不会先回收前台服务。因为前台服务有焦点把,我估计是这样的。
Bound Service
对于一个Component
对象,调用bindService(Intent aIntent)
来绑定一个Service
。
绑定之后,在Service
里面onBind(Intent intent)
里面Intent
就是bindService(Intent aIntent)
中的aIntent
对象。
二:生命周期
Stared Service
当调用startService()
的完成后,该方法立即返回,然后Android System调用Service
的onCreate()
方法(只在第一次的时候调用),然后再调用onStartCommand()
方法,这时Service
进入Active Lifetime。然后该Service
就无限的运行下去,直到Service
内部调用