在android中Activity负责前台界面展示,service负责后台的需要长期运行的任务。Activity和Service之间的通信主要由IBinder负责。在需要和Service通信的Activity中实现ServiceConnection接口,并且实现其中的onServiceConnected和onServiceDisconnected方法。然后在这个Activity中还要通过如下代码绑定服务:
Java代码
Intent intent =newIntent().setClass(this, IHRService.class);
bindService( intent , this, Context.BIND_AUTO_CREATE );
当调用bindService方法后就会回调Activity的onServiceConnected,在这个方法中会向Activity中传递一个IBinder的实例,Acitity需要保存这个实例。代码如下:
Java代码
publicvoidonServiceConnected( ComponentName inName , IBinder serviceBinder) {
if( inName.getShortClassName().endsWith("IHRService") ) {
try{
this.serviceBinder= serviceBinder;
mService = ( (IHRService.MyBinder) serviceBinder).getService();
//mTracker = mService.mConfiguration.mTracker;
} catch(Exception e) {}
}
}
在Service中需要创建一个实现IBinder的内部类(这个内部类不一定在Service中实现,但必须在Service中创建它)。
Java代码
publicclassMyBinderextendsBinder {
//此方法是为了可以在Acitity中获得服务的实例
publicIHRService getService() {
returnIHRService.this;
}
//这个方法主要是接收Activity发向服务的消息,data为发送消息时向服务传入的对象,replay是由服务返回的对象
publicbooleanonTransact(intcode , Parcel data , Parcel reply ,intflags ) {
//called when client calls transact on returned Binder
returnhandleTransactions( code , data , reply , flags );
}
}
然后在Service中创建这个类的实例:
Java代码
publicIBinder onBind( Intent intent ) {
IBinder result = null;
if(null== result ) result =newMyBinder() ;
returnresult;
}
这时候如果Activity向服务发送消息,就可以调用如下代码向服务端发送消息:
Java代码
inSend = Parcel.obtain();
serviceBinder.transact( inCode , inSend , null, IBinder.FLAG_ONEWAY );
这种方式是只向服务端发送消息,没有返回值的。如果需要从服务端返回某些值则可用如下代码:
Java代码
result = Parcel.obtain();
serviceBinder.transact( inCode , inSend , result , 0);
returnresult;
发送消息后IBinder接口中的onTransact将会被调用。在服务中如果有结果返回(比如下载数据)则将结果写入到result参数中。在Activity中从result中读取服务执行的结果。
上面只是描述了如何由Acitity向Service发送消息,如果Service向Activity发送消息则可借助于BroadcastReceiver实现,BroadcastReceiver比较简单,前面在将Service中已有提及。