1 service两种用法:
1.1 Context.startService(Intent service)
Context.stopService(Intent service) //Service.stopSelf() , Service.stopSelfResult()
1.2 Context.bindService(Intent service, ServiceConnection conn, int flags)
Context.unbindService(ServiceConnection conn)
You can bind to a service that was started with startService().
In cases like this, stopService() will not actually stop the service until the last binding is closed.
注意:bindService不可用于xml形式的BroadcastReceiver。(应用:startService(),Service.stopSelf(int))
bindService可用于动态注册的BroadcastReceiver
在bindService和unbindService的时候最好能够有一个布尔类型来控制是否已经bind
2 service生命周期方法:
2.1 startService
void onCreate() //初始化(建立线程) 只会建立一次
void onStart(Intent intent) //可多次运行。
void onDestroy() //释放资源(关闭线程) 最后运行。只要还有与service关联的部件存在,就不会调用此方法
The entire lifetime of a service happens between the time onCreate() is called and the time onDestroy() returns.
The active lifetime of a service begins with a call to onStart().
The onCreate() and onDestroy() methods are called for all services, whether they're started by Context.startService() or Context.bindService().
However, onStart() is called only for services started by startService().
2.2 bind
IBinder onBind(Intent intent)
boolean onUnbind(Intent intent)
void onRebind(Intent intent)
3 binder机制
要调用Service的public方法,需要通过Binder机制来实现
首先,Service组件本身要实现Binder机制,然后,Activity才能通过Binder连接到Service组件,并调用其public方法。
因此,第一步是给Service添加Binder支持。在Service内部添加一个Binder的内部类声明,添加getService()方法并返回Service的当前实例,
然后,实例化并持有一个Binder的引用:
下一步,覆写onBind()方法,返回binder实例:
绑定一个Service也是通过Intent完成的,同时需要提供一个ServiceConnection回调接口,用于接收Bind事件:
绑定Service后,Activity就获得了Service实例的引用,我们将其保存在成员变量中,然后,在Activity的生命周期中,就可以随时调用Service的public业务方法了。
IPC:interprocess communication 进程间通信
如果在Service的onCreate或onStart做一些很耗时的动作,最好是启动一个新线程来运行这个Service