Android绑定服务:为什么我们要将这个IBinder实例强制转换为IBinder示例



在绑定服务的开发人员文档中,为"创建绑定服务"中的"扩展绑定器类"提供了以下代码示例。给出了以下代码片段(我已经删除了不相关的位),其中Service从其onBind()方法返回IBinder

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; //**********************************************************
    }
    ...
}

然后在我们的客户端中,我们在ServiceConnectiononServiceConnected()方法中接收mBinder对象(它是LocalBinder的实例)我的问题是,为什么我们要在语句LocalBinder binder = (LocalBinder) service;中将作为argumentonServiceConnected()传递的LocalBinder的实例强制转换为LocalBinder实例

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;
        }
    };
    ...
}

ServiceConnection.onServiceConnected()的定义是

public void onServiceConnected(ComponentName className,IBinder服务)

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

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

相关内容

  • 没有找到相关文章

最新更新