我是安卓新手, 我必须编写一个服务(在不同的进程上)来处理我的互联网通信功能, 我查看了一些博客,发现使用 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 callingonBind()
again.
在 bound-service 中查找
我的建议是在你的 IBinder
中添加 register 方法来区分不同的操作。
关于android - 使用 onBind 方法接收命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14752388/