2

我已经创建了一个服务,并且对于服务间通信,我正在使用带有 Handler 的 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 中有多少消息。

我在网上搜索,但找不到有关该主题的任何内容。

关于如何获取消息列表/计数的任何线索?

4

1 回答 1

3

Square 有一篇关于如何监视Looper队列的博客文章:https ://corner.squareup.com/2013/12/android-main-thread-2.html

以下是他们对 main 的处理方式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);
    }
  }
}
于 2015-03-16T10:53:20.330 回答