In the developer docs for Bound Services, the following code example is given for "Extending the Binder Class" in "Creating a Bound Service". The following code snippet (I have removed irrelevant bits) is given in which the Service
returns an IBinder
from its onBind()
method:
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; //**********************************************************
}
...
}
Then in our client, we receive the mBinder
object (which is an instance of LocalBinder
) in the onServiceConnected()
method of ServiceConnection
. My question is that why are we trying to cast an instance of LocalBinder
passed in as an argument
to onServiceConnected()
into a LocalBinder
instance in the statement 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;
}
};
...
}
The definition of ServiceConnection.onServiceConnected() is
public void onServiceConnected(ComponentName className, IBinder service)
Note that the parameter is an IBinder
- ServiceConnection
does not know what kind of service or what kind of IBinder
implementation the service is returning - only you know that, hence why you need to cast it to the correct type.