我创建了一项服务,并且为了进行跨服务通信,我使用的是带有处理程序的Messenger。
public class LocalHandler extends Handler
{
public void handleMessage(Message message)
{
String msg = message.getData().getString("MyString");
String serv_msg = message.getData().getString("FromService");
Toast.makeText(getApplicationContext(), msg+serv_msg,
Toast.LENGTH_SHORT).show();
}
}
final Messenger myMessenger = new Messenger(new LocalHandler());
现在我想在任何特定时间检查信使的MessageQueue中有多少消息。
我在网上搜索但却无法找到有关该主题的内容。
关于如何获取消息列表/计数的任何线索?
答案 0 :(得分:2)
Square上有一篇关于如何监视Looper
队列的博客帖子:https://corner.squareup.com/2013/12/android-main-thread-2.html
以下是他们如何为主Looper
执行此操作:
public class MainLooperSpy {
private final Field messagesField;
private final Field nextField;
private final MessageQueue mainMessageQueue;
public MainLooperSpy() {
try {
Field queueField = Looper.class.getDeclaredField("mQueue");
queueField.setAccessible(true);
messagesField = MessageQueue.class.getDeclaredField("mMessages");
messagesField.setAccessible(true);
nextField = Message.class.getDeclaredField("next");
nextField.setAccessible(true);
Looper mainLooper = Looper.getMainLooper();
mainMessageQueue = (MessageQueue) queueField.get(mainLooper);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void dumpQueue() {
try {
Message nextMessage = (Message) messagesField.get(mainMessageQueue);
Log.d("MainLooperSpy", "Begin dumping queue");
dumpMessages(nextMessage);
Log.d("MainLooperSpy", "End dumping queue");
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public void dumpMessages(Message message) throws IllegalAccessException {
if (message != null) {
Log.d("MainLooperSpy", message.toString());
Message next = (Message) nextField.get(message);
dumpMessages(next);
}
}
}