Android Service(服务)
一、前言
二、正文
context.startService() -> onCreate() -> OnStartCommand()或者(onStart()) -> Service running -> context.stopService() -> onDestroy() -> Service
stop
注:
A、 OnStratCommand()是在android2.0(API-5)以后引入的代替掉onStart事件。虽然他们提供的功能一样。但是使用onStart()启动,它返回的值会控制当Service被运行时终止后,系统应该如何响应Service的重新启动。
再次我要说一下,执行一个Service并控制它的重新启动行为。
@Override public int onStartCommand(Intent intent, int flags, int startId) { // TODO Auto-generated method stub return 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; } } @Override public IBinder onBind(Intent arg0) { return binder; }
MainActivity.java
private MyService myService; /** * 处理Service和activity之间进行连接和数据传递 */ private ServiceConnection mConnection=new ServiceConnection() { @Override public void onServiceConnected(ComponentName arg0, IBinder mbinderService) { //当建立连接时调用 myService=((MyService.MyBinder)mbinderService).getService(); } @Override public void onServiceDisconnected(ComponentName arg0) { //当service意外断开时 myService=null; } };
启动BindService()
//绑定Service Intent bindIntent=new Intent(this,MyService.class); bindService(bindIntent, mConnection, flags);
flags参数说明:
用来提高Service优先级,等等功能。参数有:BIND_ADJUST_WITH_ACTIVITY、BIND_IMPORTANT等等。
3、停止service
三,补充