0

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

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()ServiceConnectionLocalBinderargumentonServiceConnected()LocalBinderLocalBinder 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;
        }
    };
    ...
}
4

2 に答える 2

3

ServiceConnection.onServiceConnected()の定義は

public void onServiceConnected(ComponentName クラス名、IBinderサービス)

IBinderパラメータは-ServiceConnectionはサービスの種類やサービスが返す実装の種類を認識していないことに注意してください-IBinderそれを知っているのはあなただけなので、正しい型にキャストする必要があるのはなぜですか。

于 2014-10-21T23:26:25.063 に答える
2

onServiceConnectedにある唯一の型情報は、type のオブジェクトを取得することですIBinderIBinders にはgetServiceIBinderメソッドがないため、オブジェクトをタイプ のオブジェクトにキャストする必要がありますLocalBinder次に、 getServiceメソッドを呼び出すことができます。これが静的型付けの仕組みです。

于 2014-10-21T23:25:35.627 に答える