理解Service

service是没有用户界面,不与用户交互,而是在后台运行一段不确定的时间的应用程序。

一,service的生命周期

service的生命周期可以由两种方式启动,一种是通过startService,另一种通过bindService。

1.1,通过startService启动

通过这种方式启动会经历: onCreate(生成)->onStart(开始)->onDestory(销毁)。

没有onResume, onPause和onStop。

通过这种方式启动,如果调用service的activity自己退出而没有调用stopService方法来销毁此service,那么这个service会一直运行下去。

1.2,通过bindService启动

通过这种方式启动会经历: onCreate(生成)->onBind(绑定)-> onUnbind(解绑)->onDestory(销毁)。

通过这种方式启动,service会和调用他的activity绑定,当这个activity推出时,service也会推出,通过调用onUnbind和onDestory,所谓绑定在一起就是共存亡。

二,创建一个service

我们可以通过IPC操作别的应用程序的Service,而创建自己的Service是通过继承Android.app.Service这个抽象类,然后根据需要重写相关方法。

对于一个服务要实现什么功能,可以onCreate和onStart里添加,如果操作需要花费很长的时间,那么最好是用个线程来以防止其造成用户使用不流畅。

2.1,创建一个startService启动的Serivce

startService(Intent service);

stopService(Intent  service);

2.2,创建一个bindService启动的Serivce

调用者和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对象。

三,注册Service

需要在AndroidMainifest.xml里注册,例如

<service android:name=”.MyService”></service>

你可能感兴趣的:(理解Service)