Android - 无法从我的服务向所有客户端发送消息
问题描述:
我使我的android服务与我的所有活动交流。一切运作良好,但今天,我想尝试从服务发送消息到所有连接的客户端。 代码在IncomingHandlerAndroid - 无法从我的服务向所有客户端发送消息
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_1:
Log.i("RpcChannelService", "MSG_1");
//send msg to all clients
Message msgGpsEnable= Message.obtain(null,
RpcChannelService.MSG_1);
for (Messenger client : mClients) {
try {
client.send(msgGpsEnable);
} catch (RemoteException e) {
Log.i("RpcChannelService", "handleMessage:MSG_GPS_ENABLE exception");
}
}
break;
}
}
当我运行/调试此代码,后通想到这个代码,程序做一个永远的循环。 谁能告诉我为什么? 非常感谢。
答
我的不好。我应该在循环内创建Message的新实例。
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_1:
Log.i("RpcChannelService", "MSG_1");
//send msg to all clients
for (Messenger client : mClients) {
try {
Message msgGpsEnable= Message.obtain(null,
RpcChannelService.MSG_1);
client.send(msgGpsEnable);
} catch (RemoteException e) {
Log.i("RpcChannelService", "handleMessage:MSG_GPS_ENABLE exception");
}
}
break;
}
}
mClients是Messenger阵列存储所有连接的客户端。 – 2014-12-13 16:21:25
它在哪里循环? – pskink 2014-12-13 18:20:01
我的不好。我应该在for循环中创建Message的新实例。 – 2015-01-07 07:00:39