0

Bound Services 的开发者文档中,“创建绑定服务”中的“扩展 Binder 类”给出了以下代码示例。给出了以下代码片段(我已删除不相关的位),其中从其方法Service返回 an :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 className, IBinder service)

请注意,参数是一个IBinder-ServiceConnection不知道服务返回的是哪种服务或哪种IBinder实现 - 只有您知道,因此您需要将其转换为正确的类型。

于 2014-10-21T23:26:25.063 回答
2

因为您在onServiceConnected中拥有的唯一类型信息是您获得了一个 type 的对象IBinderIBinders 没有getService方法,因此您必须将IBinder对象强制转换为 type 的对象LocalBinder。然后就可以调用getService方法了。这就是静态类型的工作原理。

于 2014-10-21T23:25:35.627 回答