Bound Servicesの開発者向けドキュメントでは、「バインドされたサービスの作成」の「Binder クラスの拡張」について、次のコード例が示されています。次のコード スニペット (無関係なビットを削除しました) は、メソッドから をService
返します 。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;
}
};
...
}