service是没有用户界面,不与用户交互,而是在后台运行一段不确定的时间的应用程序。
service的生命周期可以由两种方式启动,一种是通过startService,另一种通过bindService。
通过这种方式启动会经历: onCreate(生成)->onStart(开始)->onDestory(销毁)。
没有onResume, onPause和onStop。
通过这种方式启动,如果调用service的activity自己退出而没有调用stopService方法来销毁此service,那么这个service会一直运行下去。
通过这种方式启动会经历: onCreate(生成)->onBind(绑定)-> onUnbind(解绑)->onDestory(销毁)。
通过这种方式启动,service会和调用他的activity绑定,当这个activity推出时,service也会推出,通过调用onUnbind和onDestory,所谓绑定在一起就是共存亡。
我们可以通过IPC操作别的应用程序的Service,而创建自己的Service是通过继承Android.app.Service这个抽象类,然后根据需要重写相关方法。
对于一个服务要实现什么功能,可以onCreate和onStart里添加,如果操作需要花费很长的时间,那么最好是用个线程来以防止其造成用户使用不流畅。
startService(Intent service);
stopService(Intent service);
调用者和Servcie之间是通过IBinder进行通信的。
看android.content.Context.bindService方法的定义:
bindService(Intent service, ServiceConnection conn, int flags)
bindServer方法需要一个ServiceConnection对象,ServiceConnection是个接口,必须实现它的两个方法:
onServiceConnected(ComponentName name, IBinder service)
onServiceDisconnected(ComponentName name)
onServiceConnected这个回调方法需要一个IBinder对象,而Service在启动的过程种会执行onBinde方法,而此方法刚好是返回一个IBinder对象。
需要在AndroidMainifest.xml里注册,例如
<service android:name=”.MyService”></service>