最近複習到了Handler一直只知道怎麼用,卻沒有仔細分析過源碼,這下就來看看安全
爲何要使用handler呢?併發
由於在安卓應用中ui操做是線程安全的,只能ui線程去操做ui組件,可是在現實開發中,可能有多個線程去併發操做ui,因此將會致使線程不安全,因此就用到了handlerasync
Looper1.主要負責建立message Queue和自身的建立 2. 消息的循環ide
public static void prepare() { prepare(true); } private static void prepare(boolean quitAllowed) { //判斷當前的對象是否爲空 ,即prepare不能調用兩次 if (sThreadLocal.get() != null) { throw new RuntimeException("Only one Looper may be created per thread"); } 建立looper對象放入線程中 sThreadLocal.set(new Looper(quitAllowed)); }
private Looper(boolean quitAllowed) { //looper對象建立了messagequeue mQueue = new MessageQueue(quitAllowed); mThread = Thread.currentThread(); }
2.looper.loopoop
public static void loop() { final Looper me = myLooper(); if (me == null) { throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread."); } 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(); for (;;) { Message msg = queue.next(); // might block if (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 logger final Printer logging = me.mLogging; if (logging != null) { logging.println(">>>>> Dispatching to " + msg.target + " " + msg.callback + ": " + msg.what); } final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs; final long traceTag = me.mTraceTag; if (traceTag != 0 && Trace.isTagEnabled(traceTag)) { Trace.traceBegin(traceTag, msg.target.getTraceName(msg)); } final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis(); final long end; try { //吧msg交給msg.target實際就是綁定的handler去處理這個方法中調用了handlemessage因此在建立handler 的時候要重寫handlemessage方法 msg.target.dispatchMessage(msg); end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis(); } finally { if (traceTag != 0) { Trace.traceEnd(traceTag); } } if (slowDispatchThresholdMs > 0) { final long time = end - start; if (time > slowDispatchThresholdMs) { Slog.w(TAG, "Dispatch took " + time + "ms on " + Thread.currentThread().getName() + ", h=" + msg.target + " cb=" + msg.callback + " msg=" + msg.what); } } 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(); } }
Looper的做用就是建立message隊列,而後吧隊列中的消息派發給handler,而後handler去處理消息post
而後咱們在去看下Handler的源碼ui
public Handler(Callback callback, boolean async) { if (FIND_POTENTIAL_LEAKS) { final Class<? extends Handler> klass = getClass(); if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) && (klass.getModifiers() & Modifier.STATIC) == 0) { Log.w(TAG, "The following Handler class should be static or leaks might occur: " + klass.getCanonicalName()); } } mLooper = Looper.myLooper(); if (mLooper == null) { throw new RuntimeException( "Can't create handler inside thread that has not called Looper.prepare()"); } mQueue = mLooper.mQueue; mCallback = callback; mAsynchronous = async; }
能夠看出handler建立的時候就會綁定他的looper並找見他的隊列this
handler有兩種發送消息的方法 send和postspa
public final boolean sendMessage(Message msg) { return sendMessageDelayed(msg, 0); }
public final boolean sendMessageDelayed(Message msg, long delayMillis) { if (delayMillis < 0) { delayMillis = 0; } return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis); }
public boolean sendMessageAtTime(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(MessageQueue queue, Message msg, long uptimeMillis) { msg.target = this; if (mAsynchronous) { msg.setAsynchronous(true); } //看出來最後調用了隊列的方法,也就是handler發出的消息,最後會保存到對應的隊列中 return queue.enqueueMessage(msg, uptimeMillis); }
因此就是一個應用的建立,系統會自動給你生成一個主線程,並在這個主線程中生成一個Looper對象來讓你和子線程之間進行消息的傳遞,Looper會建立一個消息隊列,當咱們在子線程中給主線程發消息的時候就須要用到handler,handler建立的時候就會去找到這個對應的looper。looper不斷的執行loop方法去發消息給隊列中 ,沒當handler去發送一個消息的時候,就吧消息加入到隊列中 ,而後隊列的loop方法就會接收到這個消息,而後消息去調用dispatchmsg方法,而後dispatchmsg方法就會調用handler中的handlemessage方法,咱們就能接收到這個消息線程