gpt4 book ai didi

android - Handler.dispatchMessage(msg) 和 Handler.sendMessage(msg) 的区别

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:07:12 30 4
gpt4 key购买 nike

当我使用 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:104-19 11:32:10.488: INFO/MainActivity(774): Thread:804-19 11:32:10.492: INFO/MainActivity(774): Handler:8 & arg1=104-19 11:32:10.635: INFO/MainActivity(774): Handler:1 & arg1=2

最佳答案

mHandler.dispatchMessage(msg) 就像直接调用handleMessage(Message msg) 不知道什么时候有用。处理程序的要点是能够将消息发送到其他线程。这就是您使用 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);
}
}

关于android - Handler.dispatchMessage(msg) 和 Handler.sendMessage(msg) 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10227219/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com