当我使用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:信息/主要活动(774):主要:1 04-19 11:32:10.488:信息/MainActivity(774):线程:8 04-19 11:32:10.492: INFO/MainActivity(774): 处理程序:8 & arg1=1 04-19 11:32:10.635:INFO/MainActivity(774):处理程序:1 & arg1=2