理解Android Handler機制

本文假定讀者對Message. Loop. MessageQuene有一定了解各拷,從開發(fā)常規(guī)用法出發(fā)严蓖,從源碼的角度來理解android handler機制,然后做出自己的理解與總結(jié)土铺!

  • 首先我們來看看Handler的習(xí)慣用法出刷。
//第一步:實例化Handler
private Handler handler=new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
           //處理收到的消息
            if(msg.what==1){
            }
            return false;
        }
    });
//第二步:使用handler發(fā)送消息
private  void  sendMessage(){
        Message message=Message.obtain();
        message.what=1;
        handler.sendMessage(message);
    }
  • 構(gòu)造方法: new Handler(Callback) 做了什么?
 public Handler(Callback callback) {
        this(callback, false);
    }
//實際調(diào)用
public Handler(Callback callback, boolean async) {
       // FIND_POTENTIAL_LEAKS的定義
    //private static final boolean FIND_POTENTIAL_LEAKS = false;
  //永遠為fasle 為什么要還這個代碼呢来氧?诫给!
  //有知道的同學(xué)希望告訴一下!@惭铩中狂!
        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());
            }
        }
      //獲得Loop類
        mLooper = Looper.myLooper();
     //問題1:為什么mLoop不為空,后文有解釋
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
//消息對列
        mQueue = mLooper.mQueue;
      //回調(diào)接口處理消息
        mCallback = callback;
        mAsynchronous = async;
    }
  • Looper.myLooper()做什么了
public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }
//為什么 sThreadLocal.get()返回不空捌苏薄胃榕?
//在哪里初始化了?

原來是ActivityThread 做了好事瞄摊!
在ActivityThread的main方法有這么一句

Looper.prepareMainLooper();
//讓我們看看實際做了什么
public static void prepareMainLooper() {
//在這里添加了loop
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }
//
private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
//這里Q帧!换帜!同學(xué)楔壤,set一個新的對象
//所以就解釋了問題1 為什么不為空了。
//原來在ActivityThread里面創(chuàng)建一個mainLoop
        sThreadLocal.set(new Looper(quitAllowed));
    }

下面代碼驗證了 我們的在activity創(chuàng)建的handler使用loop的是mainLoop

boolean is=handler.getLooper().equals(Looper.getMainLooper());
   //返回true 親測惯驼!
  • 在ActivityThread#main方法還有一個重要操作
Looper.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.");
        }
        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();
      //一個無盡的loop
        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 {
                //重點看這里分發(fā)消息了
               //target是Handler實例
                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();
        }
    }


handler.sendMessage(message); 做了什么递瑰?

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);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

queue.enqueueMessage(msg, uptimeMillis);
又做了什么?隙畜!

//將消息加入隊列抖部!
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) {
                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.next
                prev.next = msg;
            }

            // We can assume mPtr != 0 because mQuitting is false.
            if (needWake) {
                nativeWake(mPtr);
            }
        }
        return true;
    }
總結(jié)

1.Message是消息的數(shù)據(jù)模型,可以存放各種消息议惰。
2.Loop 是一個永動機慎颗,不斷從消息隊列里讀出消息。
3.MessageQuene是一個消息隊列言询,不過是鏈表實現(xiàn)的數(shù)據(jù)結(jié)構(gòu)俯萎。
4.Handler是一個操作器,將消息傳入MessageQuene运杭,當(dāng)Loop讀出數(shù)據(jù)時讯屈,Handler的Callback回調(diào)處理消息。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末县习,一起剝皮案震驚了整個濱河市涮母,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌躁愿,老刑警劉巖叛本,帶你破解...
    沈念sama閱讀 219,039評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異彤钟,居然都是意外死亡来候,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,426評論 3 395
  • 文/潘曉璐 我一進店門逸雹,熙熙樓的掌柜王于貴愁眉苦臉地迎上來营搅,“玉大人,你說我怎么就攤上這事梆砸∽剩” “怎么了?”我有些...
    開封第一講書人閱讀 165,417評論 0 356
  • 文/不壞的土叔 我叫張陵帖世,是天一觀的道長休蟹。 經(jīng)常有香客問我,道長日矫,這世上最難降的妖魔是什么赂弓? 我笑而不...
    開封第一講書人閱讀 58,868評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮哪轿,結(jié)果婚禮上盈魁,老公的妹妹穿的比我還像新娘。我一直安慰自己窃诉,他們只是感情好杨耙,可當(dāng)我...
    茶點故事閱讀 67,892評論 6 392
  • 文/花漫 我一把揭開白布姓惑。 她就那樣靜靜地躺著,像睡著了一般按脚。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上敦冬,一...
    開封第一講書人閱讀 51,692評論 1 305
  • 那天辅搬,我揣著相機與錄音,去河邊找鬼脖旱。 笑死堪遂,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的萌庆。 我是一名探鬼主播溶褪,決...
    沈念sama閱讀 40,416評論 3 419
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼践险!你這毒婦竟也來了猿妈?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,326評論 0 276
  • 序言:老撾萬榮一對情侶失蹤巍虫,失蹤者是張志新(化名)和其女友劉穎彭则,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體占遥,經(jīng)...
    沈念sama閱讀 45,782評論 1 316
  • 正文 獨居荒郊野嶺守林人離奇死亡俯抖,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,957評論 3 337
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了瓦胎。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片芬萍。...
    茶點故事閱讀 40,102評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖搔啊,靈堂內(nèi)的尸體忽然破棺而出柬祠,到底是詐尸還是另有隱情,我是刑警寧澤负芋,帶...
    沈念sama閱讀 35,790評論 5 346
  • 正文 年R本政府宣布瓶盛,位于F島的核電站,受9級特大地震影響示罗,放射性物質(zhì)發(fā)生泄漏惩猫。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,442評論 3 331
  • 文/蒙蒙 一蚜点、第九天 我趴在偏房一處隱蔽的房頂上張望轧房。 院中可真熱鬧,春花似錦绍绘、人聲如沸奶镶。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,996評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽厂镇。三九已至纤壁,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間捺信,已是汗流浹背酌媒。 一陣腳步聲響...
    開封第一講書人閱讀 33,113評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留迄靠,地道東北人秒咨。 一個月前我還...
    沈念sama閱讀 48,332評論 3 373
  • 正文 我出身青樓,卻偏偏與公主長得像掌挚,于是被迫代替她去往敵國和親雨席。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,044評論 2 355

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