編輯:關於Android編程
轉載請標明出處:http://blog.csdn.net/lmj623565791/article/details/38377229 ,本文出自【張鴻洋的博客】
很多人面試肯定都被問到過,請問Android中的Looper , Handler , Message有什麼關系?本篇博客目的首先為大家從源碼角度介紹3者關系,然後給出一個容易記憶的結論。
說了這一堆,那麼和Handler 、 Looper 、Message有啥關系?其實Looper負責的就是創建一個MessageQueue,然後進入一個無限循環體不斷從該MessageQueue中讀取消息,而消息的創建者就是一個或多個Handler 。
public static final void prepare() { if (sThreadLocal.get() != null) { throw new RuntimeException("Only one Looper may be created per thread"); } sThreadLocal.set(new Looper(true)); }
private Looper(boolean quitAllowed) { mQueue = new MessageQueue(quitAllowed); mRun = true; mThread = Thread.currentThread(); }在構造方法中,創建了一個MessageQueue(消息隊列)。
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 Printer logging = me.mLogging; if (logging != null) { logging.println(">>>>> Dispatching to " + msg.target + " " + msg.callback + ": " + msg.what); } 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.recycle(); } }
public Handler() { this(null, false); } 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; }
14行:通過Looper.myLooper()獲取了當前線程保存的Looper實例,然後在19行又獲取了這個Looper實例中保存的MessageQueue(消息隊列),這樣就保證了handler的實例與我們Looper實例中MessageQueue關聯上了。
然後看我們最常用的sendMessage方法
public final boolean sendMessage(Message msg) { return sendMessageDelayed(msg, 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); }
輾轉反則最後調用了sendMessageAtTime,在此方法內部有直接獲取MessageQueue然後調用了enqueueMessage方法,我們再來看看此方法:
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) { msg.target = this; if (mAsynchronous) { msg.setAsynchronous(true); } return queue.enqueueMessage(msg, uptimeMillis); }
enqueueMessage中首先為meg.target賦值為this,【如果大家還記得Looper的loop方法會取出每個msg然後交給msg,target.dispatchMessage(msg)去處理消息】,也就是把當前的handler作為msg的target屬性。最終會調用queue的enqueueMessage的方法,也就是說handler發出的消息,最終會保存到消息隊列中去。
現在已經很清楚了Looper會調用prepare()和loop()方法,在當前執行的線程中保存一個Looper實例,這個實例會保存一個MessageQueue對象,然後當前線程進入一個無限循環中去,不斷從MessageQueue中讀取Handler發來的消息。然後再回調創建這個消息的handler中的dispathMessage方法,下面我們趕快去看一看這個方法:
public void dispatchMessage(Message msg) { if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); } }
/** * Subclasses must implement this to receive messages. */ public void handleMessage(Message msg) { }可以看到這是一個空方法,為什麼呢,因為消息的最終回調是由我們控制的,我們在創建handler的時候都是復寫handleMessage方法,然後根據msg.what進行消息處理。
例如:
private Handler mHandler = new Handler() { public void handleMessage(android.os.Message msg) { switch (msg.what) { case value: break; default: break; } }; };
1、首先Looper.prepare()在本線程中保存一個Looper實例,然後該實例中保存一個MessageQueue對象;因為Looper.prepare()在一個線程中只能調用一次,所以MessageQueue在一個線程中只會存在一個。
2、Looper.loop()會讓當前線程進入一個無限循環,不端從MessageQueue的實例中讀取消息,然後回調msg.target.dispatchMessage(msg)方法。
3、Handler的構造方法,會首先得到當前線程中保存的Looper實例,進而與Looper實例中的MessageQueue想關聯。
4、Handler的sendMessage方法,會給msg的target賦值為handler自身,然後加入MessageQueue中。
5、在構造Handler實例時,我們會重寫handleMessage方法,也就是msg.target.dispatchMessage(msg)最終調用的方法。
好了,總結完成,大家可能還會問,那麼在Activity中,我們並沒有顯示的調用Looper.prepare()和Looper.loop()方法,為啥Handler可以成功創建呢,這是因為在Activity的啟動代碼中,已經在當前UI線程調用了Looper.prepare()和Looper.loop()方法。
今天有人問我,你說Handler的post方法創建的線程和UI線程有什麼關系?
其實這個問題也是出現這篇博客的原因之一;這裡需要說明,有時候為了方便,我們會直接寫如下代碼:
mHandler.post(new Runnable() { @Override public void run() { Log.e("TAG", Thread.currentThread().getName()); mTxt.setText("yoxi"); } });
public final boolean post(Runnable r) { return sendMessageDelayed(getPostMessage(r), 0); }
private static Message getPostMessage(Runnable r) { Message m = Message.obtain(); m.callback = r; return m; }
注:產生一個Message對象,可以new ,也可以使用Message.obtain()方法;兩者都可以,但是更建議使用obtain方法,因為Message內部維護了一個Message池用於Message的復用,避免使用new 重新分配內存。
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); }最終和handler.sendMessage一樣,調用了sendMessageAtTime,然後調用了enqueueMessage方法,給msg.target賦值為handler,最終加入MessagQueue.
可以看到,這裡msg的callback和target都有值,那麼會執行哪個呢?
其實上面已經貼過代碼,就是dispatchMessage方法:
public void dispatchMessage(Message msg) { if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); } }第2行,如果不為null,則執行callback回調,也就是我們的Runnable對象。
好了,關於Looper , Handler , Message 這三者關系上面已經敘述的非常清楚了。
最後來張圖解:
希望圖片可以更好的幫助大家的記憶~~<喎?/kf/ware/vc/" target="_blank" class="keylink">vcD48aDI+NKGiuvO7sDwvaDI+PHA+xuTKtUhhbmRsZXKyu732v8nS1Lj80MJVSaOsxOPN6sirv8nS1NTa0ru49tfTz9+zzNbQyKW0tL2o0ru49khhbmRsZXKjrMi7uvPKudPD1eK49mhhbmRsZXLKtcD91NrIzrrOxuTL+8/fs8zW0Leiy83P+8+io6zX7tbVtKbA7c/7z6K1xLT6wuu2vLvh1NrE47S0vahIYW5kbGVyyrXA/bXEz9+zzNbQ1MvQ0KGjPC9wPjxwPjwvcD48cHJlIGNsYXNzPQ=="brush:java;">new Thread()
{
private Handler handler;
public void run()
{
Looper.prepare();
Looper.loop();
handler = new Handler()
{
public void handleMessage(android.os.Message msg)
{
Log.e("TAG",Thread.currentThread().getName());
};
};
};
}.start();
Android不僅給我們提供了異步消息處理機制讓我們更好的完成UI的更新,其實也為我們提供了異步消息處理機制代碼的參考~~不僅能夠知道原理,最好還可以將此設計用到其他的非Android項目中去~~
0和1是計算機的基礎,數理邏輯中0和1代表兩種狀態,真與假.0和1看似簡單,其實變化無窮. 今天我就來聊聊android控件中擁有著0和1這種特性的魔力控件checkbo
今天我們來看一下一個內存洩漏檢測神器 leakcanary(https://github.com/square/leakcanary)首先我們來看一下leakcanary
本篇介紹Listview的顯示,對於listview有許多的適配器,如ArrayAdapter,BaseAdapter,SimpleAdapter等等。本篇先熱身一下,介
安卓6.0 Marshmallow棉花糖版本雖然普及率依然可憐至極,但這並不能阻擋Google開發並推出下一個版本Android N,預計將會是