android - 使用 onBind 方法接收命令

标签 android bind

我是安卓新手, 我必须编写一个服务(在不同的进程上)来处理我的互联网通信功能, 我查看了一些博客,发现使用 Messenger 我们可以在 Activity 和服务(在不同的进程上)之间进行通信,

我的问题在这里,到目前为止我正在做这样的事情:

private Messenger _commandReceiver = new Messenger(new CommandDispatcher());

public IBinder onBind(Intent intent) {
    return _commandReceiver.getBinder();
}

class CommandDispatcher extends Handler {
    public void handleMessage(Message message) {
    int command = data.getInt("command");
    Messenger activityMessenger = (Messenger) data.get("messenger");

    switch (command) {
                case Command.IS_AUTHENTICATED:
        break;
        ...
    }
}
}

但为什么我不应该在 onBind 方法上发送命令变量和 Activity 信使并在那里处理整个事件,这样可以完全删除服务信使并且通信代码更简单, 会变成这样

public IBinder onBind(Intent intent) {

    Bundle data = intent.getExtras();
    int command = data.getInt("command");
    Messenger activityMessenger = (Messenger) data.get("messenger");

    switch (command) {
                case Command.IS_AUTHENTICATED:
        break;
        ...
    }
}

我知道这可能是一个非常简单的问题,但我在任何地方都找不到答案,所以如果有人能帮助我,我将不胜感激

最佳答案

你的问题可能在官方文档中得到解决。

正如谷歌所说,

Multiple clients can connect to the service at once. However, the system calls your service's onBind() method to retrieve the IBinder only when the first client binds. The system then delivers the same IBinder to any additional clients that bind, without calling onBind() again.

bound-service 中查找

我的建议是在你的 IBinder 中添加 register 方法来区分不同的操作。

关于android - 使用 onBind 方法接收命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14752388/

相关文章:

android - Kotlin 中的错误(改造)预期为 BEGIN_ARRAY,但在第 1 行第 2 列路径 $ 处为 BEGIN_OBJECT

java - 如何解决 Stripe xamarin 绑定(bind)错误? (CS0103 名称 'Start' 在当前上下文中不存在)

linux - 如何将驱动程序与 USB 设备绑定(bind)?

javascript - 使用javascript更改网格框的颜色

JavaScript - 处理 'this' 指针和自定义参数的最佳方法

javascript - 为什么相同的 Mocha 测试在第一个之后失败了?

android - startActivity 创建一个新的 Activity 而不是放在前面(标志集)

Android 证书固定与公钥固定

Android 的 ArrayAdapter - 添加字符串 ListView 而不是替换

android - 与前台服务android通信