android 如何从特定服务解除绑定?

oyxsuwqo  于 2022-11-20  发布在  Android
关注(0)|答案(2)|浏览(231)

我有一个绑定的服务,它使用同一个ServiceConnection对象绑定多个服务。在onServiceConnected中,我将每个服务的ComponentName和Binder保存在一个Map中,这样我就可以单独使用它们。在某个时候,我想单独解除绑定其中的一些服务。在Android中有办法做到这一点吗?
我能够找到解除绑定服务的唯一方法是使用unbindService(ServiceConnection),但我不认为我可以使用它解除绑定特定的服务。
为什么这似乎是不支持的?有什么缺点吗?

e0bqpujr

e0bqpujr1#

下面是绑定和取消绑定服务示例代码

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);
}
busg9geu

busg9geu2#

尽管库和为Android中的较低版本提供支持的时间已经过去,但它工作正常,我也使用嵌套在主服务中的服务,连接工作或通过主服务。它们是多个好的注意,当您通过Intent启动连接时,您必须以同样的方式关闭它,当服务被应用程序中的其他进程重用时,它会在进程管理中产生问题。当关闭连接并示例化一个新的连接时,它在进程中创建了一个小错误,没有正确终止。只是到mention how it is currently完成!快乐的代码!

相关问题