Android - 无法从我的服务向所有客户发送消息

时间:2014-12-13 16:12:04

标签: android

我让我的Android服务与我的所有活动交流。一切正常,但今天,我想尝试从服务发送消息到所有连接的客户端。 IncomingHandler中的代码

@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;
          }
    }

当我运行/调试此代码时,在考虑此代码后,程序会进行永久循环。 谁能告诉我为什么? 非常感谢。

1 个答案:

答案 0 :(得分:0)

我的坏。我应该在循环中创建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;
      }
}