Handler源碼學(xué)習(xí)

Handler我們經(jīng)常用砸烦,一般是用在子線程給主線程發(fā)消息,通知主線程做更新UI的操作杨拐,但是現(xiàn)在假如說(shuō)哗脖,讓你在主線程給子線程發(fā)消息呢瀑踢?

public class MainActivity extends Activity {

private MyLinearLayout mParent;
private Handler subHandler;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    init();
    Button button = findViewById(R.id.my_button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            subHandler.sendEmptyMessage(0);
        }
    });
}

private void init() {
    new Thread("子線程哈哈") {
        @Override
        public void run() {
            //創(chuàng)建looper對(duì)象,并與當(dāng)前線程綁定
            Looper.prepare();
            subHandler = new Handler(new Handler.Callback() {
                @Override
                public boolean handleMessage(Message msg) {
                    Toast.makeText(MainActivity.this, "當(dāng)前線程:" + Thread.currentThread()
                            .getName() , Toast.LENGTH_SHORT).show();
                    return true;
                }
            });
            //輪詢Looper里面的消息隊(duì)列
            Looper.loop();
        }
    }.start();
}

上面就是使用Handler在主線程給子線程發(fā)消息的demo才避,點(diǎn)擊按鈕后橱夭,主線程發(fā)消息給子線程,子線程收到消息后桑逝,Toast的結(jié)果是:當(dāng)前線程:子線程哈哈. 但是如果我把Looper.prepare();去掉棘劣,就會(huì)報(bào)錯(cuò):java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

對(duì)比在主線程創(chuàng)建handler,在子線程給主線程發(fā)消息的使用方式肢娘,唯一的區(qū)別就是加了2行代碼:

    Looper.prepare();
    ........
    Looper.loop();

那為什么呈础,在主線程中創(chuàng)建handler,我們直接new就可以橱健,但是在子線程不行呢?Hanlder的工作原理是什么沙廉?源碼是最好的老師拘荡,所以下面學(xué)習(xí)一下Handler的源碼

學(xué)習(xí)Handler的源碼之前,首先回顧一下一般情況下Handler的基本使用步驟:

1撬陵, 在主線程直接創(chuàng)建一個(gè)Handler對(duì)象珊皿,重寫(xiě)或?qū)崿F(xiàn)handlerMessage(),在handlerMessage() 里面寫(xiě)收到消息后的處理邏輯
2巨税, 在子線程中需要通知主線程的地方蟋定,調(diào)用handler.sendMessage()

只有2步,使用起來(lái)很簡(jiǎn)單. 我們就順著這個(gè)使用步驟去看Handler的源碼草添,看它到底怎么工作的驶兜,怎么就能夠讓2個(gè)不同的線程之間能夠通信

Handler的構(gòu)造方法:
public Handler() {
    this(null, false);
}


public Handler(Callback callback) {
    this(callback, false);
}


public Handler(Looper looper) {
    this(looper, null, false);
}


public Handler(Looper looper, Callback callback) {
    this(looper, callback, false);
}


public Handler(boolean async) {
    this(null, async);
}

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());
        }
    }
  //從當(dāng)前線程的ThreadLocalMap里面查找有沒(méi)有對(duì)應(yīng)的looper
    mLooper = Looper.myLooper();
    if (mLooper == null) {
        throw new RuntimeException(
            "Can't create handler inside thread that has not called Looper.prepare()");
    }
    mQueue = mLooper.mQueue;      //將looper的Queue賦值handler的成員mQueue 
    mCallback = callback;
    mAsynchronous = async;
}


public Handler(Looper looper, Callback callback, boolean async) {
    mLooper = looper;
    mQueue = looper.mQueue;
    mCallback = callback;
    mAsynchronous = async;
}
Looper.myLooper()

Handler有7個(gè)重載的構(gòu)造方法,我們直接看倒數(shù)第二種構(gòu)造方式远寸,可以看到調(diào)用了mLooper = Looper.myLooper();

 public static @Nullable Looper myLooper() {
    return sThreadLocal.get();
}

sThreadLocalLooper類的一個(gè)靜態(tài)成員抄淑,它是一個(gè)ThreadLocal

 static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

所以通過(guò)上面的代碼可以看到,Looper.myLooper()就是取出當(dāng)前線程的ThreadLocalMap里面存儲(chǔ)的key為Looper的靜態(tài)成員sThreadLocal所對(duì)應(yīng)的looper對(duì)象.(有關(guān)ThreadLoca知識(shí)驰后,請(qǐng)前往深入理解 Java 之 ThreadLocal 工作原理

如果當(dāng)前線程(Handler在哪個(gè)線程創(chuàng)建就代表哪個(gè)線程)的ThreadLocalMap里面沒(méi)有Looper對(duì)象肆资,就會(huì)報(bào)錯(cuò)提示:不能在沒(méi)有調(diào)用Looper.prepare()的線程里創(chuàng)建Handler對(duì)象,如果有Looper灶芝,就將LoopermQueue賦值給Handler的成員mQueue

Looper.prepare()

前面提到郑原,如果要?jiǎng)?chuàng)建Handler對(duì)象唉韭,必須要有Looper,如果沒(méi)有Looper犯犁,會(huì)報(bào)錯(cuò)提示要調(diào)用Looper.prepare()才可以創(chuàng)建属愤,接下來(lái)就看一下Looper.prepare()

 private static void prepare(boolean quitAllowed) {
    if (sThreadLocal.get() != null) {
        throw new RuntimeException("Only one Looper may be created per thread");
    }
    sThreadLocal.set(new Looper(quitAllowed));
}

先從當(dāng)前線程的ThreadLocalMap里面去取出key為Looper類的靜態(tài)成員sThreadLocal對(duì)應(yīng)的looper對(duì)象,如果已經(jīng)有l(wèi)ooper,就報(bào)錯(cuò):每一個(gè)線程只能有一個(gè)looper對(duì)象. 如果沒(méi)有l(wèi)ooper栖秕,就新建一個(gè)春塌,并存入當(dāng)前線程的ThreadLocalMap,存入的key是Looper類的sThreadLocal. 看到這里簇捍,我們可能會(huì)想平時(shí)我們用的時(shí)候并沒(méi)有去調(diào)用Looper.prepare()只壳,其實(shí)是系統(tǒng)已經(jīng)幫我們做了:

//ActivityThread#main()
 public static void main(String[] args) {
     ........

    Looper.prepareMainLooper();

    ActivityThread thread = new ActivityThread();
    thread.attach(false);

    if (sMainThreadHandler == null) {
        sMainThreadHandler = thread.getHandler();
    }

    if (false) {
        Looper.myLooper().setMessageLogging(new
                LogPrinter(Log.DEBUG, "ActivityThread"));
    }

    // End of event ActivityThreadMain.
    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
    Looper.loop();

    throw new RuntimeException("Main thread loop unexpectedly exited");
}

在應(yīng)用程序的入口ActivityThreadmain()方法里面(ActivityThread不是一個(gè)線程,只是一個(gè)普通類)暑塑,調(diào)用 了Looper.prepareMainLooper();

 public static void prepareMainLooper() {
    //新建一個(gè)looper對(duì)象,并存進(jìn)ThreadLocalMap
    prepare(false);
    synchronized (Looper.class) {
        if (sMainLooper != null) {
            throw new IllegalStateException("The main Looper has already been prepared.");
        }
        //給主線程對(duì)應(yīng)的looper賦值
        sMainLooper = myLooper();
    }
}

Looper也有一個(gè)獲取主線程對(duì)應(yīng)的looper的方法getMainLooper()

 public static Looper getMainLooper() {
    synchronized (Looper.class) {
        return sMainLooper;
    }
}

再看一下Looper的構(gòu)造方法:

private Looper(boolean quitAllowed) {
    //Looper對(duì)象創(chuàng)建的時(shí)候吼句,會(huì)創(chuàng)建一個(gè) MessageQueue
    mQueue = new MessageQueue(quitAllowed);
    //Looper對(duì)應(yīng)的線程
    mThread = Thread.currentThread();
}
Handler初始化過(guò)程總結(jié)

從前面Handler的創(chuàng)建過(guò)程源碼可以得出:

1,創(chuàng)建Handler對(duì)象之前事格,必須要先創(chuàng)建Looper惕艳,Looper與線程對(duì)應(yīng),一個(gè)線程只能有一個(gè)Looper
2驹愚,創(chuàng)建Handler對(duì)象之前远搪,會(huì)先檢查Handler對(duì)象創(chuàng)建時(shí)所在的線程是否已經(jīng)有一個(gè)對(duì)應(yīng)的Looper,檢查是通過(guò)調(diào)用Looper.myLooper()方法逢捺,內(nèi)部原理是通過(guò)每個(gè)線程內(nèi)部的ThreadLocalMap查找key為Looper的靜態(tài)成員ThreadLocal對(duì)應(yīng)的Looper對(duì)象是否為null
3谁鳍,如果Handler對(duì)象創(chuàng)建時(shí)所在的線程沒(méi)有對(duì)應(yīng)的Looper,那么會(huì)拋異常劫瞳,在主線程創(chuàng)建除外倘潜。所以在主線程以外的線程創(chuàng)建Handler之前要先調(diào)用Looper.prepare()創(chuàng)建一個(gè)Looper,該方法內(nèi)部同時(shí)會(huì)把Looper的靜態(tài)成員ThreadLocal作為key志于,把Looper對(duì)象做為value值涮因,存進(jìn)Handler對(duì)象創(chuàng)建時(shí)所在的線程的ThreadLocalMap,Looper就與當(dāng)前線程對(duì)應(yīng)了
4伺绽,Looper對(duì)象創(chuàng)建的時(shí)候养泡,會(huì)創(chuàng)建一個(gè)MessageQueue,該MessageQueue會(huì)在構(gòu)造Handler對(duì)象的時(shí)候憔恳,賦值給Handler的成員mQueue瓤荔,Looper對(duì)象本身也會(huì)賦值給Handler的成員mLooper

消息的發(fā)送

有了Handler對(duì)象后,就可以發(fā)送消息了钥组,看一下Handler發(fā)送消息的方法:

public final boolean sendMessage(Message msg){
    return sendMessageDelayed(msg, 0);
}

public final boolean sendEmptyMessage(int what)
{
    return sendEmptyMessageDelayed(what, 0);
}


public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
    Message msg = Message.obtain();
    msg.what = what;
    return sendMessageDelayed(msg, delayMillis);
}

public final boolean sendEmptyMessageAtTime(int what, long uptimeMillis) {
    Message msg = Message.obtain();
    msg.what = what;
    return sendMessageAtTime(msg, uptimeMillis);
}


public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
    if (delayMillis < 0) {
        delayMillis = 0;
    }
    //第二個(gè)參數(shù)傳遞的是從系統(tǒng)開(kāi)機(jī)到當(dāng)前時(shí)間的毫秒數(shù)+延遲時(shí)間
    return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}

//第二個(gè)參數(shù)uptimeMillis表示消息發(fā)送的時(shí)間
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
    //Handler的成員mQueue就是構(gòu)造Handler對(duì)象時(shí)输硝,Looper里面的MessageQueue
    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);
}

public final boolean sendMessageAtFrontOfQueue(Message msg) {
    MessageQueue queue = mQueue;
    if (queue == null) {
        RuntimeException e = new RuntimeException(
            this + " sendMessageAtTime() called with no mQueue");
        Log.w("Looper", e.getMessage(), e);
        return false;
    }
   //發(fā)送消息到消息隊(duì)列的頭部,因?yàn)榈谌齻€(gè)參數(shù)傳的是0
    return enqueueMessage(queue, msg, 0);
}

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
    //把Handler賦值給Message的target程梦,后面從消息隊(duì)列取出消息后就是交給這個(gè)target(Handler)處理
    msg.target = this;
    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
    return queue.enqueueMessage(msg, uptimeMillis);
}

上面那么多發(fā)送消息的方法点把,除了sendMessageAtFrontOfQueue()以外橘荠,其余都是調(diào)用sendMessageAtTime(),這兩個(gè)方法其實(shí)也是一樣的郎逃,sendMessageAtTime()的第二個(gè)參數(shù)傳0這兩個(gè)方法就是一樣了哥童。但是這兩個(gè)方法最終都調(diào)用了enqueueMessage(),而enqueueMessage()又調(diào)用了MessageQueueenqueueMessage()褒翰,也就是把消息插入到消息隊(duì)列

消息入隊(duì)
 boolean enqueueMessage(Message msg, long when) {
    if (msg.target == null) {
        throw new IllegalArgumentException("Message must have a target.");
    }
    if (msg.isInUse()) {
        throw new IllegalStateException(msg + " This message is already in use.");
    }

    synchronized (this) {
        if (mQuitting) {    //如果消息隊(duì)列退出了,還入隊(duì)就報(bào)錯(cuò)
            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();    //消息入隊(duì)后贮懈,標(biāo)記為在被使用
        msg.when = when;
        Message p = mMessages;
        boolean needWake;
        if (p == null || when == 0 || when < p.when) {
           //p為null(代表MessageQueue沒(méi)有消息) 或者消息的發(fā)送時(shí)間是隊(duì)列中最早的
            msg.next = p;
            mMessages = msg;
            needWake = mBlocked;  //當(dāng)阻塞時(shí)需要喚醒
        } 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;
            //將消息按時(shí)間順序插入到MessageQueue
            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.next
            prev.next = msg;
        }

        // We can assume mPtr != 0 because mQuitting is false.
        if (needWake) {
            nativeWake(mPtr);
        }
    }
    return true;
}
Looper.loop();

消息插入到消息隊(duì)列了,肯定要取出來(lái)才能用优训,從消息隊(duì)列取消息的方法就是開(kāi)頭demo中的Looper.loop();

 public static void loop() {
  //取出當(dāng)前線程對(duì)應(yīng)的looper
    final Looper me = myLooper();
    if (me == null) {
        throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
    }
    //取出looper里面的消息隊(duì)列
    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();
    //死循環(huán)
    for (;;) {
        Message msg = queue.next(); // 從消息隊(duì)列取出消息朵你,會(huì)阻塞
        if (msg == null) {
            // No message indicates that the message queue is quitting.
            return;
        }

        .......
        try {
            //分發(fā)消息,把消息交給msg.target也就是Handler處理
            msg.target.dispatchMessage(msg);
            end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
        } finally {
            if (traceTag != 0) {
                Trace.traceEnd(traceTag);
            }
        }

        ........

        msg.recycleUnchecked();    //將不再使用的消息放入消息池
    }
}
消息出隊(duì)

取消息的時(shí)候揣非,調(diào)用了消息隊(duì)列的消息出隊(duì)方法next()

//MessageQueue #next()
 Message next() {
    final long ptr = mPtr;    
    if (ptr == 0) {    //當(dāng)消息循環(huán)已經(jīng)退出抡医,則直接返回
        return null;
    }
    int pendingIdleHandlerCount = -1;  // 循環(huán)迭代的首次為-1
    int nextPollTimeoutMillis = 0;
    for (;;) {
        if (nextPollTimeoutMillis != 0) {
            Binder.flushPendingCommands();
        }
        nativePollOnce(ptr, nextPollTimeoutMillis);
        synchronized (this) {
            // Try to retrieve the next message.  Return if found.
            final long now = SystemClock.uptimeMillis();
            Message prevMsg = null;
            Message msg = mMessages;
            if (msg != null && msg.target == null) {
               //如果消息沒(méi)有 target,那它就是一個(gè)屏障早敬,需要一直往后遍歷找到第一個(gè)異步的消息
                do {
                    prevMsg = msg;
                    msg = msg.next;
                } while (msg != null && !msg.isAsynchronous());
            }
            if (msg != null) {
                if (now < msg.when) { //如果這個(gè)消息還沒(méi)到處理時(shí)間忌傻,就設(shè)置個(gè)時(shí)間過(guò)段時(shí)間再處理
                    nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                } else {
                  // 正常消息的處理
                    mBlocked = false;
                    if (prevMsg != null) {
                        prevMsg.next = msg.next;   //取出當(dāng)前消息,鏈表頭結(jié)點(diǎn)后移一位
                    } else {
                        mMessages = msg.next;
                    }
                    msg.next = null;
                    if (DEBUG) Log.v(TAG, "Returning message: " + msg);
                    msg.markInUse();
                    return msg;
                }
            } else {
                //沒(méi)有消息
                nextPollTimeoutMillis = -1;
            }

            // Process the quit message now that all pending messages have been handled.
            if (mQuitting) {
                dispose();
                return null;
            }
            if (pendingIdleHandlerCount < 0
                    && (mMessages == null || now < mMessages.when)) {
                pendingIdleHandlerCount = mIdleHandlers.size();
            }
            if (pendingIdleHandlerCount <= 0) {
                // No idle handlers to run.  Loop and wait some more.
                mBlocked = true;
                continue;
            }

            if (mPendingIdleHandlers == null) {
                mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
            }
            mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
        }

        // We only ever reach this code block during the first iteration.
        for (int i = 0; i < pendingIdleHandlerCount; i++) {
            final IdleHandler idler = mPendingIdleHandlers[i];
            mPendingIdleHandlers[i] = null; // release the reference to the handler

            boolean keep = false;
            try {
                keep = idler.queueIdle();
            } catch (Throwable t) {
                Log.wtf(TAG, "IdleHandler threw exception", t);
            }

            if (!keep) {
                synchronized (this) {
                    mIdleHandlers.remove(idler);
                }
            }
        }
        pendingIdleHandlerCount = 0;
        nextPollTimeoutMillis = 0;
    }
}
Handler.dispatchMessage()

Looper.loop()里面從消息取出消息后搞监,調(diào)用了msg.target.dispatchMessage(msg);

  public void dispatchMessage(Message msg) {
    if (msg.callback != null) {      //
        handleCallback(msg);
    } else {
        if (mCallback != null) {    //構(gòu)造Handler的時(shí)候傳入的Callback
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        handleMessage(msg);   //構(gòu)造Handler時(shí)候水孩,Callback如果傳null,就走這里,它是空實(shí)現(xiàn)
    }
}

一般情況下琐驴,我們使用Handler都是使用 Handler handler=new Handler()這種構(gòu)造方式荷愕,通過(guò)前面Handler的構(gòu)造方法源碼可以知道,這種構(gòu)造方式的mCallback傳的是null(不是Message的callback)棍矛,所以當(dāng)handler取出消息要處理的時(shí)候,會(huì)回調(diào)handleMessage(msg);而它是空實(shí)現(xiàn)抛杨,所以我們需要覆寫(xiě)handleMessage()

那么什么時(shí)候會(huì)調(diào)用if條件語(yǔ)句里面的handleCallback(msg)呢够委,其實(shí)Handler不僅只有sendMessageXXX發(fā)送消息方法,還有postXXX發(fā)送消息的方法

public final boolean post(Runnable r)
{
   return  sendMessageDelayed(getPostMessage(r), 0);
}

public final boolean postAtTime(Runnable r, long uptimeMillis)
{
    return sendMessageAtTime(getPostMessage(r), uptimeMillis);
}

public final boolean postAtTime(Runnable r, Object token, long uptimeMillis)
{
    return sendMessageAtTime(getPostMessage(r, token), uptimeMillis);
}

public final boolean postDelayed(Runnable r, long delayMillis)
{
    return sendMessageDelayed(getPostMessage(r), delayMillis);
}

public final boolean postAtFrontOfQueue(Runnable r)
{
    return sendMessageAtFrontOfQueue(getPostMessage(r));
}

有5個(gè)postXXX發(fā)送消息的方法怖现,但還是調(diào)用了sendXXX方法茁帽,只是傳遞參數(shù)的過(guò)程中調(diào)用了一個(gè)getPostMessage()

private static Message getPostMessage(Runnable r) {
    Message m = Message.obtain();
    m.callback = r;
    return m;
}

看到這里就明白了,只有調(diào)用postXXX發(fā)送消息的方法屈嗤,才會(huì)走Handler.dispatchMessage()的if語(yǔ)句里面的回調(diào)潘拨,其實(shí)我們常用更新UI的方式:Activity.runOnUiThread(Runnable), View.post(Runnable);和View.postDelayed(Runnable action, long delayMillis)都是調(diào)用Handler的post方法發(fā)送消息

 //Activity#runOnUiThread
 public final void runOnUiThread(Runnable action) {
    if (Thread.currentThread() != mUiThread) {
        mHandler.post(action);  //這個(gè)Handler是Activity的成員變量
    } else {
        action.run();
    }
 }

 //View#post
 public boolean post(Runnable action) {
    final AttachInfo attachInfo = mAttachInfo;
    if (attachInfo != null) {
        return attachInfo.mHandler.post(action);
    }

    // Postpone the runnable until we know on which thread it needs to run.
    // Assume that the runnable will be successfully placed after attach.
    getRunQueue().post(action);
    return true;
 }
關(guān)于Message的其他知識(shí)

1,Message的成員what表示的是消息的類型(用于標(biāo)識(shí)干什么用的)
2饶号,獲取一個(gè)Message對(duì)象最好的方式不是直接new铁追,而是使用Message.obtain(),或者Handler.obtainMessage()這種方式會(huì)復(fù)用消息池中的消息茫船,而不是新建

最后再總結(jié)一下Handler機(jī)制:

1琅束,每一個(gè)Handler創(chuàng)建的時(shí)候必須要有一個(gè)Looper(要么傳入扭屁,要么通過(guò)當(dāng)前線程獲取),每一個(gè)Looper對(duì)應(yīng)一個(gè)線程和MessageQueue涩禀,一個(gè)線程可以創(chuàng)建多個(gè)Handler料滥,但只能創(chuàng)建一個(gè)Looper
2,如果Handler創(chuàng)建時(shí)所在的線程和Looper創(chuàng)建時(shí)所在的線程是同一個(gè)線程艾船,Handler對(duì)象創(chuàng)建的時(shí)候會(huì)通過(guò)當(dāng)前線程的ThreadLocal的內(nèi)部類ThreadLocalMap檢查當(dāng)前線程是否已經(jīng)有一個(gè)Looper葵腹,如果是在主線程創(chuàng)建的Handler,Looper的創(chuàng)建和輪詢消息隊(duì)列的操作屿岂,主線程已經(jīng)在ActivityThread已經(jīng)幫我們做了践宴,如果不是在主線程創(chuàng)建的Handler,需要我們自己手動(dòng)調(diào)用Looper.prepare()來(lái)創(chuàng)建Looper和調(diào)用Looper.loop()輪詢消息隊(duì)列雁社,如果我們不手動(dòng)調(diào)用浴井,會(huì)報(bào)錯(cuò)!特別注意:Handler的創(chuàng)建線程可以和Looper的創(chuàng)建線程不是同一個(gè)線程
3霉撵,Handler對(duì)象創(chuàng)建的時(shí)候磺浙,會(huì)把Looper持有的MessageQueue賦值給Handler的MessageQueue,同時(shí)也會(huì)把Looper賦值給Handler的Looper徒坡,Handler發(fā)消息其實(shí)是把消息發(fā)送到Looper的MessageQueue撕氧,也就是說(shuō)Handler持有的Looper在哪個(gè)線程創(chuàng)建的(Looper.prepare()Looper.loop()一般都會(huì)在一個(gè)線程),消息也就發(fā)給哪個(gè)線程
4喇完,發(fā)送消息的過(guò)程中伦泥,Handler會(huì)把自身設(shè)置為當(dāng)前消息的Target(Handler.enqueueMessage()里面設(shè)置),這樣即使在一個(gè)線程創(chuàng)建了多個(gè)Handler锦溪,接收的Handler就永遠(yuǎn)是那個(gè)發(fā)送的Handler不脯,而不會(huì)是別的Handler,別且這多個(gè)Handler共用一個(gè)Looper和MessageQueue

感謝
https://blog.csdn.net/yanbober/article/details/45936145

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末刻诊,一起剝皮案震驚了整個(gè)濱河市防楷,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌则涯,老刑警劉巖复局,帶你破解...
    沈念sama閱讀 217,657評(píng)論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異粟判,居然都是意外死亡亿昏,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,889評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門(mén)档礁,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)角钩,“玉大人,你說(shuō)我怎么就攤上這事⊥希” “怎么了野舶?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,057評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)宰衙。 經(jīng)常有香客問(wèn)我平道,道長(zhǎng),這世上最難降的妖魔是什么供炼? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,509評(píng)論 1 293
  • 正文 為了忘掉前任一屋,我火速辦了婚禮,結(jié)果婚禮上袋哼,老公的妹妹穿的比我還像新娘冀墨。我一直安慰自己,他們只是感情好涛贯,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,562評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布诽嘉。 她就那樣靜靜地躺著,像睡著了一般弟翘。 火紅的嫁衣襯著肌膚如雪虫腋。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 51,443評(píng)論 1 302
  • 那天稀余,我揣著相機(jī)與錄音悦冀,去河邊找鬼。 笑死睛琳,一個(gè)胖子當(dāng)著我的面吹牛盒蟆,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播师骗,決...
    沈念sama閱讀 40,251評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼历等,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了辟癌?” 一聲冷哼從身側(cè)響起募闲,我...
    開(kāi)封第一講書(shū)人閱讀 39,129評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎愿待,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體靴患,經(jīng)...
    沈念sama閱讀 45,561評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡仍侥,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,779評(píng)論 3 335
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了鸳君。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片农渊。...
    茶點(diǎn)故事閱讀 39,902評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖或颊,靈堂內(nèi)的尸體忽然破棺而出砸紊,到底是詐尸還是另有隱情传于,我是刑警寧澤,帶...
    沈念sama閱讀 35,621評(píng)論 5 345
  • 正文 年R本政府宣布醉顽,位于F島的核電站沼溜,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏游添。R本人自食惡果不足惜系草,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,220評(píng)論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望唆涝。 院中可真熱鬧找都,春花似錦、人聲如沸廊酣。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,838評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)亡驰。三九已至晓猛,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間隐解,已是汗流浹背鞍帝。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,971評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留煞茫,地道東北人帕涌。 一個(gè)月前我還...
    沈念sama閱讀 48,025評(píng)論 2 370
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像续徽,于是被迫代替她去往敵國(guó)和親蚓曼。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,843評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容

  • 【Android Handler 消息機(jī)制】 前言 在Android開(kāi)發(fā)中钦扭,我們都知道不能在主線程中執(zhí)行耗時(shí)的任務(wù)...
    Rtia閱讀 4,838評(píng)論 1 28
  • 一纫版、提出問(wèn)題 面試時(shí)常被問(wèn)到的問(wèn)題: 簡(jiǎn)述 Android 消息機(jī)制 Android 中 Handler,Loop...
    Marker_Sky閱讀 2,262評(píng)論 0 18
  • 前言 在Android開(kāi)發(fā)的多線程應(yīng)用場(chǎng)景中客情,Handler機(jī)制十分常用 今天其弊,我將手把手帶你深入分析Handle...
    BrotherChen閱讀 474評(píng)論 0 0
  • 1. 前言 在之前的圖解Handler原理最后留下了幾個(gè)課后題,如果還沒(méi)看過(guò)那篇文章的膀斋,建議先看那篇文章梭伐,課后題如...
    唐江旭閱讀 5,936評(píng)論 5 45
  • 異步消息處理線程啟動(dòng)后會(huì)進(jìn)入一個(gè)無(wú)限的循環(huán)體之中,每循環(huán)一次仰担,從其內(nèi)部的消息隊(duì)列中取出一個(gè)消息糊识,然后回調(diào)相應(yīng)的消息...
    cxm11閱讀 6,425評(píng)論 2 39