当我使用Handler.dispatchMessage(msg)时,handleMessage(Message msg)将在新线程上运行,但是当我使用Handler.sendMessage(msg)时,handleMessage(Message msg)将在主线程上运行,谁可以告诉我和他们之间的区别.
谢谢!
演示:
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(); }
}
输出:
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)就像直接调用handleMessage(Message msg),我不知道什么时候会有用. Handlers的重点是能够向其他线程发送消息.这就是你用sendMessage做的事情.
编辑:你可以看到它只是为你调用handleMessage().
/** * 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); } }