远程服务拒绝绑定

时间:2016-03-21 16:06:23

标签: java android android-service android-binder

我有一个远程服务,外部应用程序可以绑定到该服务。在某些情况下,我可能希望拒绝绑定。 According to the documentation

  

将通信频道返回给服务。如果,可能会返回null   客户端无法绑定到该服务。

@Override
public IBinder onBind(final Intent intent) {
    return null;
}

返回null确实不会返回IBinder对象,因此会阻止连接,但调用应用程序无法正确接收此信息'。

boolean bound = context.bindService(intent, serviceConnection, flagsHere);

无论是否从服务返回null,这总是返回true?

According to the documentation

  

返回 - 如果您已成功绑定到该服务,则为true   回;如果未建立连接,则返回false,这样您就可以   没有收到服务对象

我曾假设从onBind返回null会导致bindService返回false。假设绝不是一个好主意......

但是返回null确实会阻止ServiceConnection实例化调用,但是这样做的结果就是没有选项来检查绑定器在onServiceConnected中是否实际为空

所以,我的问题 - 应用程序如何知道'如果绑定请求被拒绝了?

此外,如果我决定暂时拒绝onRebind(之前从onUnbind返回true)的请求被拒绝,我似乎无法覆盖此行为以阻止此操作:< / p>

@Override
public void onRebind(final Intent intent) {

    if (shouldAllowRebind(intent)) {
        super.onRebind(intent);
    } else {
        // ?
    }
}

我希望有人能为我揭开光明。提前谢谢。

1 个答案:

答案 0 :(得分:7)

您可能需要创建一种解决方法。我在这里看到两个选项:

  • 如果请求被拒绝,则返回没有任何功能的Binder。然后客户端必须检查是否存在所需的功能。
  • 始终返回相同的Binder,但如果不允许通话,则让每个方法抛出Exception(例如SecurityException)。 (这也是@CommonsWare在评论中提出的)

我个人更喜欢第二种方法,因为它更灵活。 (例如允许每次通话许可/拒绝,解决重新绑定后拒绝其他内容的问题等)。