Android Handler源碼分析

一、源碼分析

1. 一般調(diào)用
 mHandler.sendEmptyMessage(100);
2. Handler.java
 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 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);
  }

3. MessageQueue.java
 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;
            // 第一次添加數(shù)據(jù)到隊(duì)列中秒梳,或者當(dāng)前 msg 的時(shí)間小于 mMessages 的時(shí)間
            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;
                    }
                }
                // 把當(dāng)前 msg 插入到列表中
                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;
  }
4.把消息都存到隊(duì)列里面去了幔崖,然后他們是怎么輪訓(xùn)的呢?(Looper.java)
  /**
   * 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.");
        }
        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 (;;) {
         // 不斷的從消息隊(duì)列里面取消息
            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
            Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }
            // 通過(guò) target 去 dispatchMessage 而 target 就是綁定的 Handler
            msg.target.dispatchMessage(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();
        }
    }
5. 這個(gè)loop是什么時(shí)候調(diào)用的呢霎奢?我們看看ActivityThread的main方法(ActivityThread.java)
public static void main(String[] args) {
        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
        SamplingProfilerIntegration.start();

        Process.setArgV0("<pre-initialized>");
        // 初始化Looper
        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);
        
        // 開(kāi)始輪訓(xùn)
        Looper.loop();

       
    }

6. 總結(jié)
  • handler.sendMessage 其實(shí)只是把我們的 Message 加入了消息隊(duì)列益愈,隊(duì)列采用的是鏈表的方式梢灭,按照 when 也就是時(shí)間排序,然后再也沒(méi)干其他蒸其;
  • Looper的loop一直輪訓(xùn)這個(gè)隊(duì)列敏释,這是一個(gè)死循環(huán),然后調(diào)用message的target枣接,就是我們寫(xiě)的Handler執(zhí)行dispatchMessage。
  • 當(dāng)Laucher啟動(dòng)一個(gè)App的時(shí)候缺谴,首先會(huì)通過(guò)zygote Fork一個(gè)進(jìn)程但惶,然后進(jìn)程會(huì)執(zhí)行ActivityThread的main函數(shù)耳鸯,在main函數(shù)里面初始化looper,執(zhí)行l(wèi)oop膀曾。

二县爬、自己手寫(xiě)

1. Handler
public class Handler {
    // 包含一個(gè)消息隊(duì)列
    MessageQueue mQueue;
    
    public Handler() {
    //獲取looper 輪訓(xùn)器。在Activity啟動(dòng)的時(shí)候創(chuàng)建
        Looper looper = Looper.myLooper();
        
        if(looper == null){
            throw new RuntimeException(
                    "Can't create handler inside thread that has not called Looper.prepare()");
        }
        
        mQueue= looper.mQueue;
    }
    
    public void sendMessage(Message message) {
        sendMessageDelayed(message,0);
    }
    
    public final boolean sendMessageDelayed(Message msg, long delayMillis)
    {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, System.currentTimeMillis() + delayMillis);
    }
    
    public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
        MessageQueue queue = mQueue;
        return enqueueMessage(queue, msg, uptimeMillis);
    }
    
    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        return queue.enqueueMessage(msg, uptimeMillis);
    }
    
    // 空方法并沒(méi)具體的實(shí)現(xiàn)
    public void handleMessage(Message msg) {
        
    }
}
2. Looper
public class Looper {
    // sThreadLocal.get() will return null unless you've called prepare().
    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
    
    public static void prepare() {
        sThreadLocal.set(new Looper());
    }

    MessageQueue mQueue;
    
    public Looper() {
        mQueue = new MessageQueue();
    }

    public static void loop() {
    //無(wú)限輪訓(xùn) 獲取隊(duì)列里面的消息
        Looper looper = myLooper();
        for(;;){
            MessageQueue queue = looper.mQueue;
            
            Message message = queue.next();
            
            if(message == null){
                return;
            }
            
            message.target.handleMessage(message);
        }
    }

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

}
3. MessageQueue
public class MessageQueue {
    private Message mMessages;

    // 按照時(shí)間排序插入
    public boolean enqueueMessage(Message msg, long when) {
        synchronized (this) {
            msg.when = when;
            Message p = mMessages;
            //按照when 的時(shí)間進(jìn)行排序插入
            if (p == null || when == 0 || when < p.when) {
                // New head, wake up the event queue if blocked.
                msg.next = p;
                mMessages = msg;
            } else {
                Message prev;
                for (;;) {
                    prev = p;
                    p = p.next;
                    if (p == null || when < p.when) {
                        break;
                    }
                }
                msg.next = p; // invariant: p == prev.next
                prev.next = msg;
            }
        }
        return true;
    }

   // 無(wú)限輪訓(xùn) 獲取下一個(gè)消息
    public Message next() {
        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        for (;;) {

            synchronized (this) {
                // Try to retrieve the next message. Return if found.
                final long now = System.currentTimeMillis();
                Message prevMsg = null;
                Message msg = mMessages;
                if (msg != null && msg.target == null) {
                    // Stalled by a barrier. Find the next asynchronous message
                    // in the queue.
                    do {
                        prevMsg = msg;
                        msg = msg.next;
                    } while (msg != null);
                }
                if (msg != null) {
                    if (now < msg.when) {
                        // Next message is not ready. Set a timeout to wake up
                        // when it is ready.
                    } else {
                        if (prevMsg != null) {
                            prevMsg.next = msg.next;
                        } else {
                            mMessages = msg.next;
                        }
                        msg.next = null;
                        return msg;
                    }
                } else {
                }

                if (pendingIdleHandlerCount <= 0) {
                    continue;
                }
            }
        }
    }
}

4. Message
public class Message {

    public Object obj;
    public Handler target;
    public long when;
    public Message next;

}
5. 因?yàn)長(zhǎng)ooper是在主線(xiàn)程中執(zhí)行的添谊,我們來(lái)寫(xiě)一個(gè)ActivityThread
public class ActivityThread {
    final H mH = new H();
    
    public void attach(boolean b) {
        Activity mainActivity = new TestActivity();
        mainActivity.onCreate();

        // 通過(guò) Handler 去執(zhí)行Activity的生命周期
        Message message = new Message();
        message.obj = mainActivity;
        mH.sendMessage(message);
    }

    private class H extends Handler {
        public void handleMessage(Message msg) {
            Activity mainActivity = (Activity) msg.obj;
            mainActivity.onResume();
        }
    }
}
6. 模擬Activity
public class Activity {

    public void onCreate(){
        
    }
    
    public void onResume(){
        
    }
    
    public TextView findViewById(int id){
        return new TextView();
    }
}
7. TestActivity
/**
 * @author 512573717@qq.com
 * @created 2018/8/23  下午7:08.
 */
public class TestActivity extends Activity {
    private static final String TAG = "TestActivity";
    private TextView mHTextView;

    private Handler mHHandler = new Handler() {

        @Override
        public void handleMessage(Message message) {
            Log.e(TAG, "當(dāng)前線(xiàn)程名稱(chēng)===="+Thread.currentThread().getName());
            mHTextView.setText((CharSequence) message.obj);
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();

        Log.e(TAG, "onCreate");
        mHTextView = findViewById(0x111111);
        new Thread(new Runnable() {
            @Override
            public void run() {

//                mHTextView.setText("I  will be  update !!!");

                Log.e(TAG, "當(dāng)前線(xiàn)程名稱(chēng)==="+Thread.currentThread().getName());

                try {
                    Thread.sleep(100);
                    Message msg = new Message();
                    msg.obj = "I  will be  update !!!";
                    mHHandler.sendMessage(msg);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }
        ).start();

    }

    @Override
    public void onResume() {
        super.onResume();
        Log.e(TAG, "onResume");
    }
}
8. 模擬UI控件TextView
public class TextView {
    private Thread mThread;
    public TextView(){
        mThread = Thread.currentThread();
    }
    
    public void setText(CharSequence text){
        checkThread();

        System.out.println("更新UI成功:"+text);
    }
    
    void checkThread() {
        if (mThread != Thread.currentThread()) {
            throw new RuntimeException(
                    "Only the original thread that created a view hierarchy can touch its views.");
        }
    }
}
9. Client
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Looper.prepare();

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

        Looper.loop();
    }

}
10 .打印結(jié)果
 1945-1945/? E/TestActivity: onCreate
 1945-1945/? E/TestActivity: onResume
 1945-1957/? E/TestActivity: 當(dāng)前線(xiàn)程名稱(chēng)===Thread-161
 1945-1945/demo.dhcc.com.handlerdemo E/TestActivity: 當(dāng)前線(xiàn)程名稱(chēng)====main
 1945-1945/demo.dhcc.com.handlerdemo I/System.out: 更新UI成功:I  will be  update !!!

三财喳、面試相關(guān)問(wèn)題

1. 為什么不能再子線(xiàn)程里面創(chuàng)建Handler
 new Thread(new Runnable() {
            @Override
            public void run() {

                Handler  handler=new Handler();
                handler.sendMessage(Message.obtain());
            }
        }).start();
        
 //

??這個(gè)時(shí)候會(huì)報(bào)錯(cuò)“Can't create handler inside thread that has not called Looper.prepare()”,查看源碼發(fā)現(xiàn)斩狱。

   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;
    }

??修改代碼

    Looper.prepare();
    Handler  handler=new Handler();
    handler.sendMessage(Message.obtain());
    Looper.loop();

??為什么這樣有可以

   public static void prepare() {
        prepare(true);
    }

    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));
    }
    
    public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

??為什么主線(xiàn)程的可以(ActivityThread.java)

public static void main(String[] args) {
        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
        SamplingProfilerIntegration.start();

    
        Process.setArgV0("<pre-initialized>");

       // 啟動(dòng)時(shí)已經(jīng)創(chuàng)建了
        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();
        
    }
總結(jié)

?? 一個(gè)Looper對(duì)應(yīng)一個(gè)線(xiàn)程耳高。存放在ThreadLocal里面。Looper必須創(chuàng)建了才有消息隊(duì)列所踊。如果沒(méi)有消息隊(duì)列Message就沒(méi)地方存泌枪。所以必須先創(chuàng)建Looper。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末秕岛,一起剝皮案震驚了整個(gè)濱河市碌燕,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌继薛,老刑警劉巖修壕,帶你破解...
    沈念sama閱讀 206,839評(píng)論 6 482
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異遏考,居然都是意外死亡慈鸠,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,543評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門(mén)诈皿,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)林束,“玉大人,你說(shuō)我怎么就攤上這事稽亏『埃” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 153,116評(píng)論 0 344
  • 文/不壞的土叔 我叫張陵截歉,是天一觀的道長(zhǎng)胖腾。 經(jīng)常有香客問(wèn)我,道長(zhǎng)瘪松,這世上最難降的妖魔是什么咸作? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 55,371評(píng)論 1 279
  • 正文 為了忘掉前任,我火速辦了婚禮宵睦,結(jié)果婚禮上记罚,老公的妹妹穿的比我還像新娘。我一直安慰自己壳嚎,他們只是感情好桐智,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,384評(píng)論 5 374
  • 文/花漫 我一把揭開(kāi)白布末早。 她就那樣靜靜地躺著,像睡著了一般说庭。 火紅的嫁衣襯著肌膚如雪然磷。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 49,111評(píng)論 1 285
  • 那天刊驴,我揣著相機(jī)與錄音姿搜,去河邊找鬼。 笑死捆憎,一個(gè)胖子當(dāng)著我的面吹牛舅柜,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播攻礼,決...
    沈念sama閱讀 38,416評(píng)論 3 400
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼业踢,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了礁扮?” 一聲冷哼從身側(cè)響起知举,我...
    開(kāi)封第一講書(shū)人閱讀 37,053評(píng)論 0 259
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎太伊,沒(méi)想到半個(gè)月后雇锡,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 43,558評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡僚焦,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,007評(píng)論 2 325
  • 正文 我和宋清朗相戀三年锰提,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片芳悲。...
    茶點(diǎn)故事閱讀 38,117評(píng)論 1 334
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡立肘,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出名扛,到底是詐尸還是另有隱情谅年,我是刑警寧澤,帶...
    沈念sama閱讀 33,756評(píng)論 4 324
  • 正文 年R本政府宣布肮韧,位于F島的核電站融蹂,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏弄企。R本人自食惡果不足惜超燃,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,324評(píng)論 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望拘领。 院中可真熱鬧意乓,春花似錦、人聲如沸约素。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,315評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至伙窃,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間样漆,已是汗流浹背为障。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 31,539評(píng)論 1 262
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留放祟,地道東北人鳍怨。 一個(gè)月前我還...
    沈念sama閱讀 45,578評(píng)論 2 355
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像跪妥,于是被迫代替她去往敵國(guó)和親鞋喇。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,877評(píng)論 2 345