本文主要是介绍从源码详细分析Handler 原理,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
终于对handler 下手了😂
先来看看源代码,要看Handler源码还是要从构造方法入手。
@Deprecatedpublic Handler(@Nullable Callback callback) {this(callback, false);}/*** Use the provided {@link Looper} instead of the default one.** @param looper The looper, must not be null.*/public Handler(@NonNull Looper looper) {this(looper, null, false);}/*** Use the provided {@link Looper} instead of the default one and take a callback* interface in which to handle messages.** @param looper The looper, must not be null.* @param callback The callback interface in which to handle messages, or null.*/public Handler(@NonNull Looper looper, @Nullable Callback callback) {this(looper, callback, false);}
默认无参的构造方法已经过时,所以从有参数的构造方法入手,一共三个,这里涉及到一个类
Looper所以简单看下Looper是个什么
Looper 类的源码还是比较简单的,主要就是ThreadLocal,MeesageQueue
其中 ThreadLocal 是静态的。可以理解为一种数据结构。他本身并不存储对象
而是通过set方法吧对象于当前线程关联起来
从下面两个方法可以看t出主要用于Thread对象创建ThreadLocalMap.而这个Thread LocalMap 的
作用就是把当前对象和T 对象用map 关联起来。在Looper 类中调用set 方法就是把 当前线程和Looper 类关联起来。
private static Looper sMainLooper; // guarded by Looper.class
private static Observer sObserver;
都提供了静态的set方法来供外部调用
public void set(T value) {Thread t = Thread.currentThread();//当前线程ThreadLocalMap map = getMap(t);if (map != null)map.set(this, value);elsecreateMap(t, value);}
void createMap(Thread t, T firstValue) {t.threadLocals = new ThreadLocalMap(this, firstValue);}
MessageQueue 更为简单 ,是用来管理Message的。Message 是个消息队列,是链式的结构。
所以整个Looper类可以理解为构造了一个MessageQueue,并将当前这个包含了MesageQueue的Looper通过ThreadLocal关联到创建Looper 的线程。
另外Looper类中还有一个静态loop()方法,从源码来看这个方法是分发消息的,但这个方法并没有被Handler类使用。而是提供给HandlerThread 等其他类来使用的。(所以很多网上说的Hander 是使用这个方法来从MessageQueue 中取出消息分发是不对的)。
这里可以参看这篇 https://blog.csdn.net/u011578734/article/details/106241075 这个作者详细的从native层解析了Handler的流程。作者提到是用nativeWake方法来实现消息循环的唤醒操作
/*** Run the message queue in this thread. Be sure to call* {@link #quit()} to end the loop.*/public static void loop() {final Looper me = myLooper();if (me == null) {throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");}if (me.mInLoop) {Slog.w(TAG, "Loop again would have the queued messages be executed"+ " before this one completed.");}me.mInLoop = true;final MessageQueue queue = me.mQueue;// Make sure the identity of this thread is that of the local process,// and keep track of what that identity token actually is.Binder.clearCallingIdentity();final long ident = Binder.clearCallingIdentity();// Allow overriding a threshold with a system prop. e.g.// adb shell 'setprop log.looper.1000.main.slow 1 && stop && start'final int thresholdOverride =SystemProperties.getInt("log.looper."+ Process.myUid() + "."+ Thread.currentThread().getName()+ ".slow", 0);boolean slowDeliveryDetected = false;for (;;) {Message msg = queue.next(); // might blockif (msg == null) {// No message indicates that the message queue is quitting.return;}// This must be in a local variable, in case a UI event sets the loggerfinal Printer logging = me.mLogging;if (logging != null) {logging.println(">>>>> Dispatching to " + msg.target + " " +msg.callback + ": " + msg.what);}// Make sure the observer won't change while processing a transaction.final Observer observer = sObserver;final long traceTag = me.mTraceTag;long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs;if (thresholdOverride > 0) {slowDispatchThresholdMs = thresholdOverride;slowDeliveryThresholdMs = thresholdOverride;}final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0);final boolean logSlowDispatch = (slowDispatchThresholdMs > 0);final boolean needStartTime = logSlowDelivery || logSlowDispatch;final boolean needEndTime = logSlowDispatch;if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {Trace.traceBegin(traceTag, msg.target.getTraceName(msg));}final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;final long dispatchEnd;Object token = null;if (observer != null) {token = observer.messageDispatchStarting();}long origWorkSource = ThreadLocalWorkSource.setUid(msg.workSourceUid);try {msg.target.dispatchMessage(msg);if (observer != null) {observer.messageDispatched(token, msg);}dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;} catch (Exception exception) {if (observer != null) {observer.dispatchingThrewException(token, msg, exception);}throw exception;} finally {ThreadLocalWorkSource.restore(origWorkSource);if (traceTag != 0) {Trace.traceEnd(traceTag);}}if (logSlowDelivery) {if (slowDeliveryDetected) {if ((dispatchStart - msg.when) <= 10) {Slog.w(TAG, "Drained");slowDeliveryDetected = false;}} else {if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, "delivery",msg)) {// Once we write a slow delivery log, suppress until the queue drains.slowDeliveryDetected = true;}}}if (logSlowDispatch) {showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", msg);}if (logging != null) {logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);}// Make sure that during the course of dispatching the// identity of the thread wasn't corrupted.final long newIdent = Binder.clearCallingIdentity();if (ident != newIdent) {Log.wtf(TAG, "Thread identity changed from 0x"+ Long.toHexString(ident) + " to 0x"+ Long.toHexString(newIdent) + " while dispatching to "+ msg.target.getClass().getName() + " "+ msg.callback + " what=" + msg.what);}msg.recycleUnchecked();}}
private Looper(boolean quitAllowed) {mQueue = new MessageQueue(quitAllowed);mThread = Thread.currentThread();}
个然后看一下Handler做了什么事情。
从Handler 最常用 send Message方法入手.sendMessage方法调用了 enqueueMessage
而enqueueMessage调用了MessageQueue类的enqueueMessage。所以handler 无论是post 方法还是直接send 最终都是调用enqueueMessage。
最终都是执行的native 方法,只不过异步的方法会初始化message的callback属性。
不过native是如何调用callback的不得而知了。getPostMessge方法初始化了Message的callback
public final boolean post(@NonNull Runnable r) {return sendMessageDelayed(getPostMessage(r), 0);}
private static Message getPostMessage(Runnable r) {Message m = Message.obtain();m.callback = r;return m;}
public final boolean sendMessageDelayed(@NonNull Message msg, long delayMillis) {if (delayMillis < 0) {delayMillis = 0;}return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);}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);}private boolean enqueueMessage(@NonNull MessageQueue queue, @NonNull Message msg,long uptimeMillis) {msg.target = this;//把当前Handler传给Messagemsg.workSourceUid = ThreadLocalWorkSource.getUid();if (mAsynchronous) {msg.setAsynchronous(true);}return queue.enqueueMessage(msg, uptimeMillis);}
看一下这个MessageQueue类的enqueueMessage 。就是判断消息的target不为空,不是异步的,就把当Message对象放到队列的末尾,并调用一个native方法nativeWake。 那么target指向的对象就是调用sendMessage方法的Handler 对 象。也就是Handler对应的Looper的MessageQueue的每一条Message的target都是这个Handler
盲猜一下这个nativeWake方法。应该就是调用Handler 的Callback并且把Message传递给call back了。这里为猜测是一次执行一条循环的取出。
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;}
那么如果现在就要自己实现一个类似于handler 的东西。当然就是用于整理思路,并不能真正意义的实现线程的通讯,因为回调方法仍然是在子线程被调用的。虽然能拿到主线程的对象,但是如果要在主线程执行代码,还是要调用runOnUiThread本质上还是使用的Activity 默认创建的Handler。而真正用于线程通讯的方法是native 的。实际的通讯是使用ThreadLocalWorkSource.getUid();方法返回当前执行sendMessage的线程的标识。而回调执行的线程应该是通过ThreadLocal关联到Looper。由于Handler保存了Looper 并且Message的target 是handler。所以能保证回调到创建Handler 的线程(至于怎么回调的,由于是native方法看不到源码)
那么最后就是根据我的理解,写的demo。源码放上来,看下我理解的大致的流程。
(这里后续看了loop方法后有重新模拟了一个demo在另一篇文章,修改的流程是增加了在创建handler的线程中死循环取出消息,简单的用while循环模拟了一下)
class MyHandler (looper: MyLooper,callback: ((MyMessage) -> Unit)?){var mLooper:MyLoopervar mQueue:MyMessageQueuevar callBack: ((MyMessage) -> Unit)? =callbackinit {mLooper=loopermQueue=looper.messageQueue}fun sendMessage(message: MyMessage){message.mHandler=thismQueue.enqueueMessage(message)}
}class MyLooper {var mThread:Threadcompanion object{var threadLocal =ThreadLocal<MyLooper>()fun myLooper():MyLooper{return threadLocal.get()}}var messageQueue: MyMessageQueueconstructor(){Log.e("threadLooper",Thread.currentThread().name)threadLocal.set(this)mThread= Thread.currentThread()messageQueue=MyMessageQueue(true)}}
class MyMessage {var what:Int=-1var next:MyMessage?=nullvar mHandler: MyHandler?=nullvar workSourceUid:String?=null
}class MyMessageQueue(isAllowQuit: Boolean) {var isAllowQuit:Boolean=isAllowQuitprivate var mMessage: MyMessage?=nullfun enqueueMessage(message: MyMessage){var isNeekWake=falseif(mMessage==null){isNeekWake=truemMessage=message}else {message.mHandler?.let {var temp: MyMessage = mMessage!!while (true) {if (temp.next == null){temp.next=messagebreak}else{temp = temp.next!!}}}}if(isNeekWake){wake()}}fun quitAll(){if(isAllowQuit){while(true){var temp:MyMessage?=mMessageif(temp!=null){mMessage=temp.nexttemp=null}else{break}}mMessage=null}}fun wake(){mMessage?.mHandler?.let {handler->handler.callBack?.let {callback->mMessage?.let {message->Log.e("thread",handler.mLooper.mThread.name)handler.mLooper.mThread//创建handler的线程对象callback(message)message.next?.let{mMessage=itwake()}}}}}
}
调用的部分,并不能真正的在UI 线程执行,只能回调UI 线程的代码
class MainModel(binding: ActivityMainBinding, context: Activity) :MyBaseModel<ActivityMainBinding>(binding, context) {var handler:MyHandler?=nullinit {bindListener(binding.tvHello)handler= MyHandler(MyLooper(),{myMessage ->Log.e("threada",Thread.currentThread().name)//子线程
////这里要执行在主线程还是需要runOnUiThread(Runnable{})})}override fun onClick(v: View?) {v?.let {when(v.id){R.id.tv_hello->{Thread(Runnable {var message= MyMessage()message.what=33handler?.sendMessage(message)}).start()}else->{}}}}
}
这篇关于从源码详细分析Handler 原理的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!