Service和组件通信
扩展Binder类
Binder是客户端和服务用来通信的接口,可以通过返回一个Binder实例,让客户端接收Binder对象并从中访问Service的公有方法。
创建Binder实例,并从Service中的onBind()方法返回该Binder实例,在客户端回调方法onServiceConnected()接收Binder。
服务和客户端之所以必须位于同一个应用程序中,是为了让客户端能够正确转换(cast)返回的对象并调用对象的API。 服务和客户端也必须位于同一个进程中,因为这种方式不能执行任何跨进程的序列化(marshalling)操作。
首先,在自定义的服务类中继承一个自己的Binder类,作为Service类的内部类。
public class MyBinder extends Binder {
MyService getService() {
return MyService.this;
}
}
该Binder返回Service的一个实例。并在Service类中定义供客户端使用的公共方法:
public long getTime() {
return System.currentTimeMillis();
}
然后在Service类中重新onBind()方法,当客户端和服务绑定时,返回上面定义的MyBinder的实例。
@Nullable
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
然后,在客户端就是Activity中定义一个ServiceConnection,并重写其中的onServiceConnected()方法。
private ServiceConnection mConnection=new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
MyService.MyBinder binder=(MyService.MyBinder)service;
myService=binder.getService();
mBound=true;
}
@Override
public void onServiceDisconnected(ComponentName name) {
mBound=false;
}
};
当连接建立时,获取Binder实例,调用getService()方法获取Service的实例,然后调用之前定义的getTime()方法。
之后,重写Activity的onStart()和onStop(),来绑定和解除服务。
@Override
protected void onStart() {
super.onStart();
Intent intent = new Intent(MainActivity.this, MyService.class);
bindService(intent,mConnection,Context.BIND_AUTO_CREATE);
}
@Override
protected void onStop() {
super.onStop();
unbindService(mConnection);
}
调用方法时,直接通过获取的Service实例执行方法即可。
long num=myService.getTime();
Log.d("test", String.valueOf(num));
打印结果
D/test﹕ 1458782762216