在Bound Services 的开发者文档中,“创建绑定服务”中的“扩展 Binder 类”给出了以下代码示例。给出了以下代码片段(我已删除不相关的位),其中从其方法Service
返回 an :IBinder
onBind()
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; //**********************************************************
}
...
}
然后在我们的客户端中,我们在 的方法中接收mBinder
对象(它是 的实例LocalBinder
)。我的问题是,为什么我们要尝试将作为to传入的实例转换为语句中的实例?onServiceConnected()
ServiceConnection
LocalBinder
argument
onServiceConnected()
LocalBinder
LocalBinder binder = (LocalBinder) service;
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;
}
};
...
}