在绑定服务的开发人员文档中,为"创建绑定服务"中的"扩展绑定器类"提供了以下代码示例。给出了以下代码片段(我已经删除了不相关的位),其中Service
从其onBind()
方法返回IBinder
:
public class LocalService extends Service {
// Binder given to clients
private final IBinder mBinder = new LocalBinder();
...
/**
* Class used for the client Binder. Because we know this service always
* runs in the same process as its clients, we don't need to deal with IPC.
*/
public class LocalBinder extends Binder {
LocalService getService() {
// Return this instance of LocalService so clients can call public methods
return LocalService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder; //**********************************************************
}
...
}
然后在我们的客户端中,我们在ServiceConnection
的onServiceConnected()
方法中接收mBinder
对象(它是LocalBinder
的实例)我的问题是,为什么我们要在语句LocalBinder binder = (LocalBinder) service;
中将作为argument
到onServiceConnected()
传递的LocalBinder
的实例强制转换为LocalBinder
实例
public class BindingActivity extends Activity {
LocalService mService;
boolean mBound = false;
...
/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className,
IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
...
}
ServiceConnection.onServiceConnected()的定义是
public void onServiceConnected(ComponentName className,IBinder服务)
请注意,参数是IBinder
-ServiceConnection
不知道服务返回的是什么类型的服务或IBinder
实现,只有您知道这一点,因此需要将其强制转换为正确的类型。
因为您在onServiceConnected中拥有的唯一类型信息是您获得了一个类型为IBinder
的对象。IBinder
没有getService方法,因此必须将IBinder
对象强制转换为LocalBinder
类型的对象。然后您可以调用getService方法。这就是静态键入的工作原理。