Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use a Messenger rather than passing the reference to a Handler?

I have a main activity and bound service. The bound service receives a command from the network, which triggers a Message to be sent to a Handler in the main activity. I got everything to work by passing the Handler's reference to the service. And then... I stumbled across this thing called a Messenger.

Messenger: Reference to a Handler, which others can use to send messages to it. This allows for the implementation of message-based communication across processes, by creating a Messenger pointing to a Handler in one process, and handing that Messenger to another process.

This inspired a few questions:

  • Does the term process mean I won't need to use a Messenger unless I generate a separate process under the Process and Thread guidelines?
  • Is it always good practice to use a Messenger?
  • Is passing a reference to the Handler typically a bad idea?
like image 302
Rich Avatar asked Jul 30 '13 06:07

Rich


2 Answers

Does the term process mean I won't need to use a Messenger unless I generate a separate process under the Process and Thread guidelines?

This is correct. You need a Messenger if you want to bind a remote service (e.g. running in another process). In this case, the only option to provide remote service with a pointer to your Handler would be to use a Messenger.

Is it always good practice to use a Messenger?

I would not say so. Use it when it's really needed - for remote services or if you start service without binding it. You can pack Messenger as an extra into an Intent and start service with it. Thus you can pass reference to a Handler without binding a service. This is another case when Messenger is useful.

Is passing a reference to the Handler typically a bad idea?

If you properly handle registration and unregistration of Handler when activity starts and stops, then you should be ok. There is no need to use Messenger for local service then. If you don't unregister handler properly, there will be memory leaks (service refers a handler, and handler refers a stopped activity).

like image 180
sergej shafarenka Avatar answered Oct 14 '22 20:10

sergej shafarenka


The main advantage of Messenger over handler is, Messenger is able to queue all the messages sent from various clients. While Handler needs a looper to do that. So messenger gives an extra edge when used in IPC among remote processes

like image 28
Gopal S Akshintala Avatar answered Oct 14 '22 22:10

Gopal S Akshintala