When sending a message between Threads, Views or Activities, there are two seemingly identical ways of doing it.
The first, and to me the most intuitive, is to obtain
a Message
, then use the Handler
's sendMessage
method:
Message msgNextLevel = Message.obtain();
msgNextLevel.what = m.what;
mParentHandler.sendMessage(msgNextLevel);
Or, you can obtain
the message providing the Handler
, then use the Message
's sendToTarget
method:
Message msg = Message.obtain(parentHandler);
msg.what = 'foo';
msg.sendToTarget();
Why do these two ways of achieving the same thing exist? Do they behave differently?
If you check Message.java code for example from here you will see
In other words,
sendToTarget()
will use a previously specifiedHandler
and invoke itssendMessage()
If you look for the
obtain()
method you will see:The explanation provided is also very good:
Doing the same for
obtain(Handler h)
:You can confirm that
obtain(Handler h)
really isobtain()
with the addition of setting the targetHandler
There are several other overloads , just check Message.java and search for "obtain"
obtain(Message orig)
obtain(Handler h, Runnable callback)
obtain(Handler h, int what)
obtain(Handler h, int what, Object obj)
obtain(Handler h, int what, int arg1, int arg2)
obtain(Handler h, int what, int arg1, int arg2, Object obj)
Hope this helps, cheers!