A
A
Alexey2016-08-06 22:37:40
Android
Alexey, 2016-08-06 22:37:40

Why do messages keep coming to the destroyed Handler?

There is Messenger and Handler, which receives messages.

private class IncomingHandler extends Handler {
  @Override
  public void handleMessage(Message msg) {
    super.handleMessage(msg);
  }
}

private IncomingHandler incomingHandler = new IncomingHandler();
private Messenger mMessenger = new Messenger(incomingHandler);

The bindService call establishes a connection to the service (successfully). A message is sent to the service, its replyTo specifies mMessenger . The service returns a response and it comes in handleMessage . Up to here everything is working as it should.
I disconnect from the service through unbindService . The service sends another message and for some reason it is again accepted by the Handler. I untie him from the calbacks, destroy him and the Messenger.
mMessenger = null;
incomingHandler.removeCallbacksAndMessages(null);
incomingHandler = null;

The service sends another message and it is again received by handleMessage at a time when the incomingHandler passed to Messenger and itself is null. I assumed that after disconnecting from the service, sending a message from it would throw an exception. How is this possible and what needs to be done to stop messages from reaching?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2016-08-07
@zagayevskiy

Handlers are not tied to the life cycle of services, incl. and on bind/unbind. In the docks they write that "Remove any pending posts of callbacks and sent messages". Nothing is said about the future.

I untie him from the calbacks, destroy him and the Messenger.
mMessenger = null;
incomingHandler.removeCallbacksAndMessages(null);
incomingHandler = null;
Resetting links to Messenger and Handler is, of course, not deleting objects. Objects continue to live perfectly, they receive messages, etc. Another thing is that you have some troubles with the life cycle of the service - after all clients have unbinded from it (unbindService), it should end and not send anything else.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question