浅谈Service

来源:互联网 发布:进度计划编制软件 编辑:程序博客网 时间:2024/06/05 11:07

Android Service(服务)

一、前言

service和activity不同,activity显示用户界面,而service运行是不可见的,它用来执行一些持续性的、耗时的操作。运行中Service具有比处于比非激活状态或者不可见状态的activity要高的优先级。
本来准备写一篇关于Service的帖子无意中,发现一个很全的帖子,于是决定,就在此贴上做一些总结和补充吧。
参考贴:http://blog.csdn.net/ithomer/article/details/7364024

二、正文

1、Service的生命周期。
                            
2、启动Service:
      有两种方式,startService()、BindService()
       context.startService() 启动流程:

          context.startService()  -> onCreate()  -> OnStartCommand()或者(onStart())  -> Service running  -> context.stopService()  -> onDestroy()  -> Service stop 

注:

    A、 OnStratCommand()是在android2.0(API-5)以后引入的代替掉onStart事件。虽然他们提供的功能一样。但是使用onStart()启动,它返回的值会控制当Service被运行时终止后,系统应该如何响应Service的重新启动。

       再次我要说一下,执行一个Service并控制它的重新启动行为

@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {// TODO Auto-generated method stubreturn Service.START_STICKY;}
onStartCommand()返回值,即设定了Service的重新启动模式,eg:STAR_STICKY、STAR_NOT_STICKY、STAR_REDELIVER_INTENT等等。

上面所说的Onstat()处理程序等同于重写了OnStartCommand()并返回STAR_STICKY.


B、在OnStartComand()返回值中,指定重新启动模式,将会影响后面的调用中 传入参数的值。

eg.intent、flags、startId的值。


通过StartService()启动service代码:

Intent intent=new Intent(this,MyService.class);startService(intent);

当然也可以隐式启动。


context.bindService()启动流程:

context.bindService()  -> onCreate()  -> onBind()  -> Service running  -> onUnbind()  -> onDestroy()  -> Service stop

通过BindService()启动Service,可以将一个activity和一个Service绑定起来,前者会维持一个对后者的实例的引用,实现对正在运行的Service进行方法调用。

代码如下:

MyService.java

 private final IBinder binder=new MyBinder();public class MyBinder extends Binder{MyService getService(){return MyService.this;}}@Overridepublic IBinder onBind(Intent arg0) {return binder;}

MainActivity.java

private MyService myService;/** * 处理Service和activity之间进行连接和数据传递 */private ServiceConnection mConnection=new ServiceConnection() {@Overridepublic void onServiceConnected(ComponentName arg0, IBinder mbinderService) {//当建立连接时调用myService=((MyService.MyBinder)mbinderService).getService();}@Overridepublic void onServiceDisconnected(ComponentName arg0) {//当service意外断开时myService=null;}};
启动BindService()

//绑定ServiceIntent bindIntent=new Intent(this,MyService.class);bindService(bindIntent, mConnection, flags);
flags参数说明:

                  用来提高Service优先级,等等功能。参数有:BIND_ADJUST_WITH_ACTIVITY、BIND_IMPORTANT等等。

3、停止service

要停止service,可以使用stopService(),并且不管statrService()被调用多少次,对于stopService的调用,就回终止所有匹配的Service.
或者使用自终止stopSelf。

三,补充

刚刚提到了提高service优先级问题,可以设置bindService(bindIntent, mConnection, flags);中flags参数,不过也易通过
startForeground()将service优先级提到前台
stopForeground()移到后台。

然后,简单提一下下次可能会谈到后台运行,下载东西:AsyncTask、Thread+Handler、android提供的Loadmanager中的Loader、IntentSerice参考:http://blog.csdn.net/ryantang03/article/details/8146154.





0 0
原创粉丝点击