Question

I have created a service and for inter-service communication I am using a Messenger with a Handler.

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());

Now I want to check at any particular time how many messages are there in the MessageQueue of the messenger.

I searched the web but couldnt find anything on the topic.

Any leads about how I can get the list/count of messages?

Était-ce utile?

La solution

There is a blog post from Square on how to spy for Looper's queue: https://corner.squareup.com/2013/12/android-main-thread-2.html

Here is how they do it for 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);
    }
  }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top