我的android 第37天 -服务--Service(二)

我的android 第37天 -服务--Service(二)

二、建立能与Activity进行相互通信的本地服务

通过startService()和stopService()启动关闭服务。适用于服务和Activity之间没有调用交互的情况。如果相互之间需要方法调用或者传递参数,需要使用bindService()和unbindService()方法启动关闭服务。

采用Context.bindService()方法启动服务,在服务未被创建时,系统会先调用服务的onCreate()方法,接着调用onBind()方法,这个时候调用者和服务绑定在一起。如果客户端要与服务进行通信,那么,onBind()方法必须返回Ibinder对象。如果调用者退出了,系统就会先调用服务的onUnbind()方法,接着调用onDestroy()方法。如果调用bindService()方法前服务已经被绑定,多次调用bindService()方法并不会导致多次创建服务及绑定(也就是说onCreate()和onBind()方法并不会被多次调用)。如果调用者希望与正在绑定的服务解除绑定,可以调用unbindService()方法,调用该方法也会导致系统调用服务的onUnbind()-->onDestroy()方法。

Activity与服务进行通信,开发人员通常把通信方法定义在接口里,然后让Ibinder对象实现该接口,而Activity通过该接口引用服务onBind()方法返回的Ibinder对象,然后调用Ibinder对象里自定义的通信方法。例子如下:

本例是一个本地服务,即服务与Activity在同一个应用内部。

接口:

publicinterface ICountService {

  public int getCount();

}

服务类:

publicclass CountServiceextends Service {

privatebooleanquit;

privateintcount;

privateServiceBinder serviceBinder =new ServiceBinder();

publicclass ServiceBinderextends Binder implements ICountService {

  @Override

  public int getCount() {

  return count;

  }

}

@Override

publicIBinder onBind(Intentintent) {

  return serviceBinder;

}

@Override

publicvoid onCreate() {

  super.onCreate();

  new Thread(new Runnable() {

  @Override

  public void run() {

  while (!quit) {

      try{

  Thread.sleep(1000);

      }catch (InterruptedException e){}

     count++;

  }

  }

  }).start();

}

@Override

publicvoid onDestroy() {

  super.onDestroy();

  this.quit =true;

}

}

客户端Activity:

publicclass ClientActivityextends Activity {

  private ICountService countService;

  @Override

  public void onCreate(BundlesavedInstanceState) {

  super.onCreate(savedInstanceState);

  setContentView(R.layout.main);

  this.bindService(newIntent(this, CountService.class), this.serviceConnection,BIND_AUTO_CREATE);

  }

  @Override

  protected void onDestroy() {

  super.onDestroy();

  this.unbindService(serviceConnection);

  } 

  private ServiceConnection serviceConnection =new ServiceConnection() {

  @Override

  public void onServiceConnected(ComponentNamename, IBinderservice) {

  countService = (ICountService)service;//对于本地服务,获取的实例和服务onBind()返回的实例是同一个

  int i = countService.getCount(); 

  Log.v("CountService","Count is " + i);

  }

  @Override

  public void onServiceDisconnected(ComponentNamename) {

  countService =null;

  }

  };

}

下载视频代码

相关推荐