3

我有一项从服务器提取数据的服务。而且我有需要更新的 gui 活动。

因此,在不同的情况下,例如从服务器成功提取信息,服务器必须向活动发出信号表明有新信息。

为此,我实现了这个功能:

    /**
 * ServerService.class
 * 
 * Sends a message to the observer that there is a new status message to be
 * pulled from the service#
 * 
 * @param pMessage
 *            the message to be set to the public status
 */
private void signalNewStatus(String pMessage) {

    //check if there is a message at all to be signaled as new
    if (pMessage != null) {
        Log.v(tag, "signalNewStatus:" + pMessage);

        // set the message
        vStatus = pMessage;

        // start the new callback via the handler
        myMessageHandler.sendEmptyMessage(I_STATUS_UPDATE_SIGNAL);
    }
}

为了处理消息,我有消息处理程序:

    private final Handler myMessageHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        Log.i(tag, "handleMessage: "+msg.what);

        switch (msg.what) {

        case I_STATUS_UPDATE_SIGNAL: {

            // Broadcast to all clients the new value.
            final int N = myCallbackList.beginBroadcast();

            for (int i = 0; i < N; i++) {
                try {
                    myCallbackList.getBroadcastItem(i).sendUpdateStatusSignal(true);

                } catch (RemoteException e) {

                }
            }
            myCallbackList.finishBroadcast();
        }
            break;

第一个函数经常被调用,我可以在日志中看到它按时正常工作。

但是消息处理的日志不会立即被调用。它被延迟并且最常在最后被调用。不知何故像散装一样。

我无法弄清楚为什么会这样。其余的运行良好,一旦处理了消息,消息就会毫无问题地到达 UI 线程。

有什么建议么?

非常感谢!

4

1 回答 1

0

如果没有更多代码,我无法确定,但这听起来像是一个线程问题。

尝试将处理程序代码放在单独的 HandlerThread 中,检索服务中的处理程序并将消息发送给它。

于 2013-05-24T09:52:45.820 回答