When I use Handler.dispatchMessage(msg)
, the handleMessage(Message msg)
will be run on new thread but when I use Handler.sendMessage(msg)
, the handleMessage(Message msg)
will be run on main thread. Who can tell me the difference between them?
Thanks!
Demo:
public class MainActivity extends Activity
{
private String TAG = "MainActivity";
private Handler mHandler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
Log.i(TAG, "Handler:" + Thread.currentThread().getId() + " & arg1=" + msg.arg1);
super.handleMessage(msg);
}
};
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.i(TAG, "Main:" + Thread.currentThread().getId());
testMethod();
}
private void testMethod()
{
Thread thread = new Thread()
{
@Override
public void run()
{
Log.i(TAG, "Thread:" + Thread.currentThread().getId());
Message msg = mHandler.obtainMessage();
msg.arg1 = 1;
mHandler.dispatchMessage(msg);
Message msg2 = mHandler.obtainMessage();
msg2.arg1 = 2;
mHandler.sendMessage(msg2);
}
};
thread.start();
}
}
Output:
04-19 11:32:10.452: INFO/MainActivity(774): Main:1 04-19 11:32:10.488: INFO/MainActivity(774): Thread:8 04-19 11:32:10.492: INFO/MainActivity(774): Handler:8 & arg1=1 04-19 11:32:10.635: INFO/MainActivity(774): Handler:1 & arg1=2
mHandler.dispatchMessage(msg)
is like directly calling handleMessage(Message msg)
and I don't know when that would be useful. The point of Handlers is the ability to send messages to other threads. That's what you do with sendMessage
.
Edit: as you can see it just calls handleMessage()
for you.
/**
* Handle system messages here.
*/
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
// callback = the Runnable you can post "instead of" Messages.
msg.callback.run();
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}