【问题标题】:How do I unbind from a specific service?如何解除与特定服务的绑定?
【发布时间】:2014-10-16 12:49:57
【问题描述】:

我有一个绑定服务,该服务又使用同一个 ServiceConnection 对象绑定多个服务。在 onServiceConnected 中,我将每个服务的 ComponentName 和 Binder 保存在 Map 中,以便我可以单独使用它们。在某个时候,我想分别解除其中一些服务的绑定。有没有办法在 Android 中做到这一点?

我能够找到解除绑定服务的唯一方法是使用 unbindService(ServiceConnection),但我认为我不能使用它解除特定服务的绑定。

为什么这似乎不受支持?有什么缺点吗?

【问题讨论】:

    标签: android service binding unbind


    【解决方案1】:

    这里是绑定和取消绑定服务的示例代码

    i = new Intent(this, YourService.class)
    
    protected ServiceConnection mServerConn = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder binder) {
        Log.d(LOG_TAG, "onServiceConnected");
    }
    
    @Override
    public void onServiceDisconnected(ComponentName name) {
        Log.d(LOG_TAG, "onServiceDisconnected");
    }
    }
    
    public void start() {
    
    mContext.bindService(i, mServerConn, Context.BIND_AUTO_CREATE);
    mContext.startService(i);
    }
    
    public void stop() {
    mContext.stopService(new Intent(mContext, ServiceRemote.class));
    mContext.unbindService(mServerConn);
    }
    

    【讨论】:

    • 谢谢,但这对我没用。如果您只连接到一项服务,这很好。我使用同一个 ServiceConnection 对象连接到多个不同的服务。那么,如果 unbindService 接受的唯一参数是 bindService 中使用的 ServiceConnection 对象,我该如何解除其中一项服务的绑定?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-09
    相关资源
    最近更新 更多