从服务发送消息到UI线程 - 服务处理程序中的消息延迟

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线程。

有什么建议吗?

非常感谢!


刚刚想到了消息冲突的问题。可能有些人会频繁发送消息,从而阻塞或延迟该消息的传递。 - Volodymyr Lykhonis
不,这不是消息接收方(UI线程)的问题,问题出现在服务端。只有服务本身才能从内部发送消息。 - user929995
1个回答

0

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接