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
If You Call the Handler.dispatchMessage()
in the Main Thread Then The Message is processed in Main Thread.
If You Call The Handler.dispatchMessage()
in the Worker Thread Then The Message is Processed in Worker Thread.
When You Call Handler.sendMessage(msg)
The Message is Processed in the Thread Which Created The Handler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With