我有一个从服务器获取数据的服务。我还有一个作为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线程。
有什么建议吗?
非常感谢!