Android开发教程:Service简析

2014-11-24 12:35:32 · 作者: · 浏览: 2

简介


Service的启动有两种方式:context.startService()和context.bindService()。

1.使用context.startService()启动Service


生命周期:
context.startService() ->onCreate()- >onStart()->Servicerunning->context.stopService()


onDestroy() ->Service stop

如果Service还没有运行,则android先调用onCreate()然后调用onStart();如果Service已经运行,则只调用onStart(),所以一个Service的onStart方法可能会重复调用多次。

stopService的时候直接onDestroy,如果是调用者自己直接退出而没有调用stopService的话,Service会一直在后台运行。该Service的调用者再启动起来后可以通过stopService关闭Service。

所以调用startService的生命周期为:onCreate --> onStart(可多次调用) --> onDestroy

2.使用context.bindService()启动Service


context.bindService()->onCreate()->onBind()->Service running


onUnbind() ->onDestroy() ->Servicestop


service可以在和多场合的应用中使用,比如播放多媒体的时候用户启动了其他Activity这个时候程序要在后台继续播放,比如检测SD卡上文件的变化,再或者在后台记录你地理信息位置的改变等等。


下面是一个实际的例子:


这个例子有四个类:






其中和Service有关的是PlayMusicActivit.java和MusicService.java


PlayMusicActivit是一个启动界面上面有四个按钮分别来启动、暂停、停止和关闭Service


MusicService是一个实际的Service类


另外连个类是用来做通知的,将在通知里面讲解