1.Handler的工作流程( 三 )


// 在主线程中创建一个 Handler 对象Handler handler = new Handler(Looper.getMainLooper()) {@Overridepublic void handleMessage(Message msg) {// 在主线程中处理消息switch (msg.what) {case MESSAGE_ID:// 处理特定的消息Object obj = msg.obj;// 执行相应的操作break;// 处理其他消息// ...}}};// 创建一个 Message 对象 , 并发送到消息队列中Message message = handler.obtainMessage();message.what = MESSAGE_ID;message.obj = someObject;handler.sendMessage(message);
总的来说 , .post() 适用于在主线程中执行简单的代码块或任务 , 而 .() 更适用于发送包含更多信息的消息 , 并需要在消息处理中进行更复杂的操作 。
其他并没有其他什么区别
我们之前看过**()**的源码
现在看看post的源码
2.2.1post的源码
public final boolean post(@NonNull Runnable r) {returnsendMessageDelayed(getPostMessage(r), 0);}
我们会发现post内部调用了(),其中传递的参数分别是与延时时间
我们再点击()的源码看看
2.2.1.()源码
public final boolean sendMessageDelayed(@NonNull Message msg, long delayMillis) {if (delayMillis < 0) {delayMillis = 0;}return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);}
它先进行了一个判断,判断延时时间是否小于0 , 小于0则给它赋值为0,然后返回()
2.2.1.()源码
public boolean sendMessageAtTime(@NonNull Message msg, long uptimeMillis) {MessageQueue queue = mQueue;if (queue == null) {RuntimeException e = new RuntimeException(this + " sendMessageAtTime() called with no mQueue");Log.w("Looper", e.getMessage(), e);return false;}return enqueueMessage(queue, msg, uptimeMillis);}
中先判断为不为空,为空的话返回一个异常
否则的话进行(),这个方法应该很眼熟,在中这个是用来添加消息的
2.2.1.3post的流程总结
post()传递的是一个,然后进入方法,它会让你把进行化与一起传进去
然后进入了方法,它会让你把与.() + 一笔给传进去,后面的这个是什么呢?给出的解释是:
然后传递(),把,msg与三个参数一起传进去,进行的插入
我们再进来看看()是怎么把msg插入到里面的
2.的源码
boolean enqueueMessage(Message msg, long when) {if (msg.target == null) {throw new IllegalArgumentException("Message must have a target.");}synchronized (this) {if (msg.isInUse()) {throw new IllegalStateException(msg + " This message is already in use.");}if (mQuitting) {IllegalStateException e = new IllegalStateException(msg.target + " sending message to a Handler on a dead thread");Log.w(TAG, e.getMessage(), e);msg.recycle();return false;}msg.markInUse();msg.when = when;Message p = mMessages;boolean needWake;if (p == null || when == 0 || when < p.when) {// New head, wake up the event queue if blocked.msg.next = p;mMessages = msg;needWake = mBlocked;} else {// Inserted within the middle of the queue.Usually we don't have to wake// up the event queue unless there is a barrier at the head of the queue// and the message is the earliest asynchronous message in the queue.needWake = mBlocked && p.target == null && msg.isAsynchronous();Message prev;for (;;) {prev = p;p = p.next;if (p == null || when < p.when) {break;}if (needWake && p.isAsynchronous()) {needWake = false;}}msg.next = p; // invariant: p == prev.nextprev.next = msg;}// We can assume mPtr != 0 because mQuitting is false.if (needWake) {nativeWake(mPtr);}}return true;}

if (p == null || when == 0 || when < p.when)