首先Service从启动方式上分为两种,StartedService、BoundService,他们都需要继承Service基类来自定义,都需要在AndroidMainFest中声明。
StartService通过Client调用Content.StartService(Intent intent)来启动,
第一次启动会执行OnCreat(),OnStartCommond(Intent intent,int flag ,int startId)
当Client再次调用Content.StartService()时只执行OnStartCommond(Intent intent,int flag,int startId)
当Client调用Context.Stop()或Service调用stopshelf()时,会执行OnDestory()结束StartedService
StartedService的生命周期是完全独立的。
BoundService通过Client调用bindService(Intent intent ,ServiceConnection sc,int flags)方法将Service绑定到此Client上,Boundservice的生命周期和绑定的Client是一致的,当Client销毁绑定的service会执行OnDestory(),当然也可以调用unBound()来解除绑定。
注意:
● StartedService和BoundService默认都是运行在主线程的,当进行耗时操作时需要在Service里 创建新的线程来执行,StartedService可以创建单独的进程,需要在声明Service时设置process标签来实现
● BroadcastReceiver不能BindService,如有此类需求可以用StartedService代替
● BoundService常用方式:1.Extendint the binder class 2.Using a Messager 3.AIDL
● Local Service(本地服务,同一进程) VS Remote Service(Started处于单独进程)
● IntentService(集成自service的特殊类,定义了OnHandlerIntent抽象类来执行长期任务,执行完毕后会自动关闭)
● 前台Service(和系统通知相关联的Service)