-
Notifications
You must be signed in to change notification settings - Fork 780
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
2020-03-04:试从源码角度分析Handler的post和sendMessage方法的区别和应用场景? #239
Comments
最简单的区别就是post 是无参回调直接new Runnable就可以实现 sendMessage有参数 post一般用于单个场景 比如单一的倒计时弹框功能 sendMessage的回调需要去实现handleMessage Message则做为参数 用于多判断条件的场景 比如3个按钮 实现不同的效果 |
handler.post和handler.sendMessage方法最后都会调用sendMessageAtTime方法进行消息的发送,但是在post方法中message是通过getPostMessage(Runnable r)这个方法获取的message,在这个方法中有这样一句代码m.callback = r ,给message的callback赋值为runnable对象,而在dispatchMessage这个方法中对消息进行分发的时候,先进行了msg.callback != null的判断,如果不为null,消息是通过handleCallback(msg);这个方法处理的,在这个方法中message.callback.run();调用的是post方法传递过来的runnable内的run方法处理消息,如果为空,再进行handler内部的callback判断mCallback != null,如果handler内的callback不为空,执行mCallback.handleMessage(msg)这个处理消息并判断返回是否为true,如果返回true,消息处理结束,如果返回false,消息交给handler的handleMessage(msg)处理。 |
post 使用的是 Runable,而 sendMessage 需要重新方法,或者设置 Callback //应用场景:感觉那个使用符合逻辑,并且方便就用那个了 |
post是将一个Runnbale封装成Message, 并赋值给callback参数,从这个过程之后就和sendMessge没有任何区别,会接着执行sendMessageDelayed->sendMessageAtTime,然后进入消息队列等待执行,到达Message执行时间时调用Handler的dispatchMessage方法,
话外:
总的来说应用场景没啥区别... |
其实没多大区别,post 只是把runnable 给 msg.callback ,而sendMessage 只是用数据给 msg,最后都是传递这个 Message。
如果 callback 不为空,则执行 handleCallback(msg); 方法,就是用ActivityThread去执行这个runnable,如果未null,就执行我们熟悉的 handleMessage(msg) |
handle的post和sendMessage方法的区别在于post是发送无参和执行自己实现的runnable 而sendMessage发送是带有message并执行handleMessage |
No description provided.
The text was updated successfully, but these errors were encountered: