【问题标题】:Android Bound Services: Why do we cast this IBinder instance into an IBinder instance?Android Bound Services:为什么我们要把这个 IBinder 实例转换成一个 IBinder 实例?
【发布时间】:2014-10-21 23:13:22
【问题描述】:

developer docs for Bound Services中“创建绑定服务”中的“扩展Binder类”给出如下代码示例。给出了以下代码 sn-p(我已删除无关位),其中 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 的一个实例)。 我的问题是,为什么我们要尝试将作为 argument 传递给 onServiceConnected()LocalBinder 的实例转换为声明 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;
        }
    };
    ...
}

【问题讨论】:

    标签: android casting android-service android-service-binding android-binder


    【解决方案1】:

    ServiceConnection.onServiceConnected()的定义是

    public void onServiceConnected(ComponentName className, IBinder 服务)

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • “如果变量的类型在编译时已知,则语言是静态类型的。这实际上意味着您作为程序员必须指定每个变量的类型”。 Reference - 现在我无法弄清楚这与静态类型有什么关系。
      • @Zarah 因为选角。您不会使用动态语言进行转换(只是失败)。当您进行强制转换时,您是在说您希望覆盖编译时可用的类型信息,因为您知道得更好。你充满活力。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-05
      • 1970-01-01
      • 2012-01-18
      • 2014-04-14
      • 1970-01-01
      • 1970-01-01
      • 2019-02-17
      相关资源
      最近更新 更多