深入了解Looper、Handler、Message之間關系

前言及簡介

前些天我們整個項目組趁著小假期,驅車去了江門市的臺山猛虎峽玩了兩個多鐘左右極限勇士全程漂流,感覺真得不錯,天氣熱就應該多多玩水,多親近一下大自然,不要整天埋頭工作。寫文章主要是讓朋友們一起相互分享學習,共同進步。
好了,言歸正題,今天我們要講的主題是關于Android中的異步消息處理機制的內(nèi)容。有一點Android基礎的朋友們都知道,在Android中,主線程(也就是UI線程)是不安全的,當在主線程處理消息過長時,非常容易發(fā)生ANR(Application Not Responding)現(xiàn)象,這樣對于用戶體驗是非常不好的;其次,如果我們在子線程中嘗試進行UI的操作,程序就可能還會直接崩潰。我相信,對于大多剛入門的朋友,在日常工作當中會經(jīng)常遇到這個問題,而解決的方法大多已經(jīng)通過google已了解清楚,也就是在子線程中創(chuàng)建一個消息Message對象,然后利用在主線程中創(chuàng)建的Handler對象進行發(fā)送,之后我們可以在這個Handler對象的handlerMessage()方法中獲取剛剛發(fā)送的Message對象,取出里面所存儲的值,就可以在這里進行UI的操作。這種方法就稱為異步消息處理線程。
總的來說,異步消息處理線程,說得比較通俗一點就是,當我們啟動此方法后,會進入到一個無限的循環(huán)當中,每循環(huán)一次,我們就其對應的內(nèi)部消息隊列(Message Queue)中取出一個消息(Message),然后回調(diào)好相應的消息處理函數(shù),當執(zhí)行完一個消息后則繼續(xù)循環(huán),若當消息隊列中消息為空,則線程會被阻塞等待,直到有消息進入時再被喚醒。
好吧,說了那么多,現(xiàn)在,就讓我們來看一下這種處理機制的廬山真面目吧。

分析Handler

首先我們來分析分析一下Handler的用法,我們知道,要創(chuàng)建一個Handler對象非常的簡單明了,直接進行new一個對象即可,但是你有沒有想過,這里會隱藏著什么注意點呢?,F(xiàn)在可以試著寫一下下面的一小段代碼,然后自己運行看看:

public class MainActivity extends ActionBarActivity {

    private Handler mHandler0;

    private Handler mHandler1;

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

        mHandler0 = new Handler();
        new Thread(new Runnable() {
            @Override
            public void run() {
                mHandler1 = new Handler();
            }
        }).start();
    }

這一小段程序代碼主要創(chuàng)建了兩個Handler對象,其中,一個在主線程中創(chuàng)建,而另外一個則在子線程中創(chuàng)建,現(xiàn)在運行一下程序,則你會發(fā)現(xiàn),在子線程創(chuàng)建的Handler對象竟然會導致程序直接崩潰,提示的錯誤竟然是Can't create handler inside thread that has not called Looper.prepare()

于是我們按照logcat中所說,在子線程中加入Looper.prepare(),即代碼如下:

new Thread(new Runnable(){
    @override
    public void run(){
        Looper.prepare();
        mHandler1 = new Handler()l
    }
}).start();

再次運行一下程序,發(fā)現(xiàn)程序不會再崩潰了,可是,單單只加這句Looper.prepare()是否就能解決問題了。我們探討問題,就要知其然,才能了解得更多。我們還是先分析一下源碼吧,看看為什么在子線程中沒有加Looper.prepare()就會出現(xiàn)崩潰,而主線程中為什么不用加這句代碼?我們看下Handler()構造函數(shù):

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

構造函數(shù)直接調(diào)用this(null, false),于是接著看其調(diào)用的函數(shù),

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

不難看出,源碼中調(diào)用了mLooper = Looper.myLooper()方法獲取一個Looper對象,若此時Looper對象為null,則會直接拋出一個“Can't create handler inside thread that has not called Looper.prepare()”異常,那什么時候造成mLooper是為空呢?那就接著分析Looper.myLooper(),

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

這個方法在sThreadLocal變量中直接取出Looper對象,若sThreadLocal變量中存在Looper對象,則直接返回,若不存在,則直接返回null,而sThreadLocal變量是什么呢?

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

它是本地線程變量,存放在Looper對象,由這也可看出,每個線程只有存有一個Looper對象,可是,是在哪里給sThreadLocal設置Looper的呢,通過前面的試驗,我們不難猜到,應該是在Looper.prepare()方法中,現(xiàn)在來看看它的源碼:

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

由此看到,我們的判斷是正確的,在Looper.prepare()方法中給sThreadLocal變量設置Looper對象,這樣也就理解了為什么要先調(diào)用Looper.prepare()方法,才能創(chuàng)建Handler對象,才不會導致崩潰。但是,仔細想想,為什么主線程就不用調(diào)用呢?不要急,我們接著分析一下主線程,我們查看一下ActivityThread中的main()方法,代碼如下:

public static void main(String[] args) {
    SamplingProfilerIntegration.start();

    // CloseGuard defaults to true and can be quite spammy.  We
    // disable it here, but selectively enable it later (via
    // StrictMode) on debug builds, but using DropBox, not logs.
    CloseGuard.setEnabled(false);

    Environment.initForCurrentUser();

    // Set the reporter for event logging in libcore
    EventLogger.setReporter(new EventLoggingReporter());

    Security.addProvider(new AndroidKeyStoreProvider());

    // Make sure TrustedCertificateStore looks in the right place for CA certificates
    final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
    TrustedCertificateStore.setDefaultUserDirectory(configDir);

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

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

    Looper.loop();

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

代碼中調(diào)用了Looper.prepareMainLooper()方法,而這個方法又會繼續(xù)調(diào)用了Looper.prepare()方法,代碼如下:

public static void prepareMainLooper() {
    prepare(false);
    synchronized (Looper.class) {
        if (sMainLooper != null) {
            throw new IllegalStateException("The main Looper has already been prepared.");
        }
        sMainLooper = myLooper();
    }
}

分析到這里已經(jīng)真相大白,主線程中google工程師已經(jīng)自動幫我們創(chuàng)建了一個Looper對象了,因而我們不再需要手動再調(diào)用Looper.prepare()再創(chuàng)建,而子線程中,因為沒有自動幫我們創(chuàng)建Looper對象,因此需要我們手動添加,調(diào)用方法是Looper.prepare(),這樣,我們才能正確地創(chuàng)建Handler對象。

發(fā)送消息

當我們正確的創(chuàng)建Handler對象后,接下來我們來了解一下怎么發(fā)送消息,有一點基礎的朋友肯定對這個方法已經(jīng)了如指掌了。具體是先創(chuàng)建出一個Message對象,然后可以利用一些方法,如setData()或者使用arg參數(shù)等方式來存放數(shù)據(jù)于消息中,再借助Handler對象將消息發(fā)送出去就可以了。

    new Thread(new Runnable() {
        @Override
        public void run() {
            Message msg = Message.obtain();
            msg.arg1 = 1;
            msg.arg2 = 2;
            Bundle bundle = new Bundle();
            bundle.putChar("key", 'v');
            bundle.putString("key","value");
            msg.setData(bundle);
            mHandler0.sendMessage(msg);
        }
    }).start();

通過Message對象進行傳遞消息,在消息中添加各種數(shù)據(jù),之后再消息通過mHandler0進行傳遞,之后我們再利用Handler中的handleMessage()方法將此時傳遞的Message進行捕獲出來,再分析得到存儲在msg中的數(shù)據(jù)。但是,這個流程到底是怎么樣的呢?具體我們還是來分析一下源碼。首先分析一下發(fā)送方法sendMessage():

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

通過調(diào)用sendMessageDelayed(msg, 0)方法

public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
    if (delayMillis < 0) {
        delayMillis = 0;
    }
    return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}

再能過調(diào)用sendMessageDelayed(Message msg, long delayMillis),方法中第一個參數(shù)是指發(fā)送的消息msg,第二個參數(shù)是指延遲多少毫秒發(fā)送,我們著重看一下此方法:

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

由這里可以分析得出,原來消息Message對象是建立一個消息隊列MessageQueue,這個對象MessageQueue由mQueue賦值,而由源碼分析得出mQueue = mLooper.mQueue,而mLooper則是Looper對象,我們由上面已經(jīng)知道,每個線程只有一個Looper,因此,一個Looper也就對應了一個MessageQueue對象,之后調(diào)用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);
}

方法通過調(diào)用MessageQueue對enqueueMessage(Message msg, long uptimeMills)方法:

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("MessageQueue", 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;
}

首先要知道,源碼中用mMessages代表當前等待處理的消息,MessageQueue也沒有使用一個集合保存所有的消息。觀察中間的代碼部分,隊列中根據(jù)時間when來時間排序,這個時間也就是我們傳進來延遲的時間uptimeMills參數(shù),之后再根據(jù)時間的順序調(diào)用msg.next,從而指定下一個將要處理的消息是什么。如果只是通過sendMessageAtFrontOfQueue()方法來發(fā)送消息

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

它也是直接調(diào)用enqueueMessage()進行入隊,但沒有延遲時間,此時會將傳遞的此消息直接添加到隊頭處,現(xiàn)在入隊操作已經(jīng)了解得差不多了,接下來應該來了解一下出隊操作,那么出隊在哪里進行的呢,不要忘記MessageQueue對象是在Looper中賦值,因此我們可以在Looper類中找,來看一看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();

    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.recycleUnchecked();
    }
}

代碼比較多,我們只挑重要的分析一下,我們可以看到下面的代碼用for(;;)進入了一個死循環(huán),之后不斷的從MessageQueue對象queue中取出消息msg,而我們不難知道,此時的next()就是進行隊列的出隊方法,next()方法代碼有點長,有興趣的話可以自行翻閱查看,主要邏輯是判斷當前的MessageQueue是否存在待處理的mMessages消息,如果有,則將這個消息出隊,然后讓下一個消息成為mMessages,否則就進入一個阻塞狀態(tài),一直等到有新的消息入隊喚醒?;乜磍oop()方法,可以發(fā)現(xiàn)當執(zhí)行next()方法后會執(zhí)行msg.target.dispatchMessage(msg)方法,而不難看出,此時msg.target就是Handler對象,繼續(xù)看一下dispatchMessage()方法:

public void dispatchMessage(Message msg) {
    if (msg.callback != null) {
        handleCallback(msg);
    } else {
        if (mCallback != null) {
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        handleMessage(msg);
    }
}

先進行判斷mCallback是否為空,若不為空則調(diào)用mCallback的handleMessage()方法,否則直接調(diào)用handleMessage()方法,并將消息作為參數(shù)傳出去。這樣我們就完全一目了然,為什么我們要使用handleMessage()來捕獲我們之前傳遞過去的信息。
現(xiàn)在我們根據(jù)上面的理解,不難寫出異步消息處理機制的線程了。

class myThread extends Thread{
    public Handler myHandler;

    @Override
    public void run() {
        Looper.prepare();
        myHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                //處理消息
            }
        };
       Looper.loop();
    }
}

當然除了發(fā)送消息外,還有以下幾個方法可以在子線程中進行UI操作:

  • View的post()方法
  • Handler的post()方法
  • Activity的runOnUiThread()方法

其實這幾個方法的本質(zhì)都是一樣的,只要我們勤于查看這幾個方法的源碼,不難看出最后調(diào)用的也是Handler機制,也是借用了異步消息處理機制來實現(xiàn)的。

總結

通過上面對異步消息處理線程的講解,我們不難真正地理解到了Handler、Looper以及Message之間的關系,概括性來說,Looper負責的是創(chuàng)建一個MessageQueue對象,然后進入到一個無限循環(huán)體中不斷取出消息,而這些消息都是由一個或者多個Handler進行創(chuàng)建處理。
接下來朋友們想要了解哪方面的東西或者有什么好的想法,可以在下面留言交流,我會盡自己的能力選擇分享給朋友們,當然,如果有什么分享錯誤或者不懂的地方,可以相互交流,期待每個朋友在我的博文中都能學到東西,如果覺得好的話,麻煩各位兄弟關注一下,謝謝?。?/strong>

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

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