Android開發之異步任務消息機制

前言

文章是一篇學習筆記,主要記錄了閱讀HandlerMessageMessageQueueLooper源碼(Android 8.1)的一些心得體會,但并沒有涉及到更深層次源碼的分析,比如MessageQueuenative層的源碼。而AsyncTask只是簡單介紹其API

概述

Android的消息機制主要是指Handler的運行機制,Handler的運行需要底層的MessageQueueLooper的支撐,常用于更新UI

MessageQueue用于存儲消息(Message),內部的存儲結構采用了鏈表,而不是隊列,它提供插入和刪除消息的功能,但不會處理消息。Looper,MessageQueue的管家,它的loop方法會一直查看MessageQueue是否存在消息(Message)需要處理,如果有,就交給Handler來處理。Handler是消息(Message)的發送者和處理者。

ThreadLocal并不是線程,它的作用是可以在每個線程中存儲數據,這些數據對于其他線程是不可見的。每個線程中只會有一個Looper,可以通過ThreadLocal獲取到。

另外,線程默認是沒有Looper的,如果需要使用Handler就必須為線程創建,比如在子線程。而主線程已經為我們創建好了,可以查閱ActivityThreadmain方法,其中包括了MessageQueue的初始化。

它們的數量級關系是:Handler(N):Looper(1):MessageQueue(1):Thread(1)

Handler的主要作用是將一個任務切換到某個指定的線程中執行,這樣設計主要是為了解決Android只能再主線程中更新UI

系統為什么不允許再子線程中訪問UI呢?這是因為AndroidUI控件不是線程安全的,如果再多線程中并發訪問可能會導致UI控件處于不可預期的狀態。

加鎖的缺點有兩個:首先加上鎖機制會讓UI訪問的邏輯變得復雜;其次,鎖機制會降低UI訪問的效率,因為鎖機制會阻塞某些線程的執行。

創建方式

在此只列出一種創建Handler的方式,其他的創建方式可以自行百度,但是,一定要注意:如果在沒有Looper的線程里創建Handler會報錯的

    // 在主線程創建
    public class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            // 處理的代碼
        }
    }

    MyHandler handler = new MyHandler();

    // 子線程中執行
    Message message = handler.obtainMessage();
    message.what = 1;
    message.obj = 123;
    handler.sendMessage(message);

原理圖

Handler原理圖(一).png
handler原理圖(二).png

源碼分析

先從ActivityThreadmain方法看起,里面有兩句需要注意的:

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

      // 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());

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

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

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

大致就是說,主線程的Looper已經準備好了。通常,我們創建Handler會選擇繼承Handler并重寫handleMessage,因為父類的handleMessage什么也不做。這里,我們關注其構造方法(無參的):

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

假如我們再子線程中創建Handler,但該線程并沒有Looper,它會拋出異常:

Can't create handler inside thread that has not called Looper.prepare()

可見,Handler的創建需要Looper。那這個異常如何解決呢?舉例如下:

new Thread("new Thread") {
        @Override
        public void run() {
            Looper.prepare();
            Handler handler = new Handler();
            Looper.loop();
        }
    }.start();

現在,我們回想一下,為什么在主線程可以直接創建Handler?正如前面所講述的,當我們的App啟動后,會調用ActivityThreadmain的方法,而LooperprepareMainLooper方法會被調用,也就是創建了Looper,也就是滿足了Handler的創建條件。其源碼如下:

/** Initialize the current thread as a looper.
  * This gives you a chance to create handlers that then reference
  * this looper, before actually starting the loop. Be sure to call
  * {@link #loop()} after calling this method, and end it by calling
  * {@link #quit()}.
  */
public static void prepare() {
    prepare(true);
}

private static void prepare(boolean quitAllowed) {
    if (sThreadLocal.get() != null) {
        // 一個線程只能創建一個Looper
        throw new RuntimeException("Only one Looper may be created per thread");
    }
    sThreadLocal.set(new Looper(quitAllowed));
 }

/**
 * Initialize the current thread as a looper, marking it as an
 * application's main looper. The main looper for your application
 * is created by the Android environment, so you should never need
  * to call this function yourself.  See also: {@link #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();
    }
}

不管是prepareMainLooper()方法還是prepare()方法,最后都是通過prepare(boolean quitAllowed)來創建Looper。我們先來看sThreadLocal

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

詳細的介紹可以參考這篇博客:Android的消息機制之ThreadLocal的工作原理。它的作用是保存當前線程的Looper,且線程間互不干擾。

再看Looper的構造方法,它完成了MessageQueue的創建:

private Looper(boolean quitAllowed) {
    mQueue = new MessageQueue(quitAllowed);
    mThread = Thread.currentThread();
}

總的來說,Android的主線程就是ActivityThread,主線程的入口方法為main,再main方法中系統會通過Looper.prepareMainLooper()來創建主線程的Looper以及MessageQueue,并通過Looper.loop()來開啟主線程的消息循環。

Message:消息載體

  • public int what:標識
  • public int arg1:保存int數據
  • public int arg2:保存int數據
  • public Object obj:保存任意數據
  • long when:記錄應該被處理的時間值,換句話說就是延時時間
  • Handler target:保存在主線程創建的Handler對象引用
  • Runnable callback:用來處理消息的回調器(一般不用,見原理圖二)
  • Meaage next:指向下一個Message用來形成一個鏈表
  • private static Message sPool:用來緩存處理過的Message,以便復用
  • Message obtain():它利用了Message中消息池(sPool

先從Message的創建入手,官方更推薦使用obtain來創建,而不是其構造方法。它的構造方法什么也不做,只是完成了Message的創建,而obtain可以復用Message,且有很多多種重載。從內存、效率來看,obtain更優。

/** Constructor (but the preferred way to get a Message is to call {@link #obtain() Message.obtain()}).
 */
public Message() {
}

/**
 * Return a new Message instance from the global pool. Allows us to
 * avoid allocating new objects in many cases.
 */
public static Message obtain() { // 最常見
    synchronized (sPoolSync) {
        if (sPool != null) {
            Message m = sPool;
            sPool = m.next;
            m.next = null;
            m.flags = 0; // clear in-use flag
            sPoolSize--;
            return m;
        }
    }
    return new Message();
}

可見,消息池采用了鏈表結構,確實是復用了Message

private static final Object sPoolSync = new Object();
private static Message sPool;
private static int sPoolSize = 0;

private static final int MAX_POOL_SIZE = 50;

下面是Message的回收處理:

/**
 * Return a Message instance to the global pool.
 * <p>
 * You MUST NOT touch the Message after calling this function because it has
 * effectively been freed.  It is an error to recycle a message that is currently
 * enqueued or that is in the process of being delivered to a Handler.
 * </p>
 */
public void recycle() {
    if (isInUse()) {
        if (gCheckRecycle) {
            throw new IllegalStateException("This message cannot be recycled because it "
                        + "is still in use.");
        }
        return;
    }
    recycleUnchecked();
}

/**
 * Recycles a Message that may be in-use.
 * Used internally by the MessageQueue and Looper when disposing of queued Messages.
 */
void recycleUnchecked() {
    // Mark the message as in use while it remains in the recycled object pool.
    // Clear out all other details.
    flags = FLAG_IN_USE;
    what = 0;
    arg1 = 0;
    arg2 = 0;
    obj = null;
    replyTo = null;
    sendingUid = -1;
    when = 0;
    target = null;
    callback = null;
    data = null;

    synchronized (sPoolSync) {
        if (sPoolSize < MAX_POOL_SIZE) {
            next = sPool;
            sPool = this;
            sPoolSize++;
        }
    }
}

前面也提到,Message可以自行處理,處理的邏輯交給一個Runnable,也就是callback,讀者可以自行查閱obtain的其他重載,看看callback賦值的情況,這里就不帖代碼了。

Handler:發送、處理、移除消息

前面已經分析過Message的相關代碼,該小節將從發送Message開始分析。其實,也可以通過Handler來創建Message,其內部也是調用Message.obtain來創建Message對象。

public final Message obtainMessage() {
    return Message.obtain(this);
}

Handler發送消息的方式有多種方式,這里選了一種最常見的,它的調用流程:

發送過程.png

源碼如下:

public final boolean sendMessage(Message msg) {
    return sendMessageDelayed(msg, 0); // 延時發送時間為0
}

// 延時發送
public final boolean sendMessageDelayed(Message msg, long delayMillis) {
    // 容錯
    if (delayMillis < 0) {
        delayMillis = 0;
    }
     // 當前時間加上延時時間就是真正發送Message的時間
    return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}

public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
    // Looper創建時,MessageQueue也創建了
    // mQueue在Handler創建是就初始化了,代碼在前面已經貼過了
    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) {
    // Message的成員變量,用來存儲Handler的對象引用
    // 也就是記錄了由哪個Handler來處理這個Message
    msg.target = this;
    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
    // 將Message插入到MessageQueue中,完成發送
    return queue.enqueueMessage(msg, uptimeMillis);
}

另外,Handlerpost方法也可以發送Message,且該Message將交給它自身來處理,當讀者看過dispatchMessage方法后就明白了。

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

private static Message getPostMessage(Runnable r) {
    Message m = Message.obtain();
    m.callback = r; // 可以回憶下講述Message的那一節
    return m;
 }

下面是dispatchMessage的源碼,它在Looper.loop方法中被調用:

public void dispatchMessage(Message msg) {
    // 如果Message.callback不為null,就交給它自身處理
    if (msg.callback != null) {
        handleCallback(msg);
    } else {
        // 如果mCallback不為null,交給該Handler處理
        // mCallback是Handler內部的一個接口
        if (mCallback != null) {
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        // 最后是我們最常見的,重寫handleMessage
        handleMessage(msg);
    }
}

接著來看看Callback,這個接口長啥樣:

public interface Callback {
    /**
     * @param msg A {@link android.os.Message Message} object
     * @return True if no further handling is desired
     */
    public boolean handleMessage(Message msg);
}

它也是在Handler創建的時候初始化的,但調用的構造方法不一樣,導致最后的初始化不一樣。無參的構造方法會導致mCallbacknull

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

最后來看看Handler移除Message的實現,但真正的實現交給了MessageQueue

public final void removeMessages(int what) {
    mQueue.removeMessages(this, what, null);
}

public final void removeMessages(int what, Object object) {
    mQueue.removeMessages(this, what, object);
}

MessageQueue:存儲消息的,以message的when排序優先級

MessageHandler發送后到達MessageQueue,它采用鏈表的數據結構來存儲Message。下面是其構造方法:

MessageQueue(boolean quitAllowed) {
    mQuitAllowed = quitAllowed;
    // 如果需要理解為什么loop方法不會卡住主線程,可以從這個本地方法開始入手
    mPtr = nativeInit();
}

MessageQueue中最主要的兩個方法是nextenqueueMessage

next方法也會阻塞(當消息隊列為空時或當前時間還沒到達Message要處理的時間點時)但不會卡住主線程,它的工作就是根據需求從消息隊列中取一個Message。注意,next方法是一個無限循環的方法。

enqueueMessage方法的工作就是將一個Message插入到消息隊列且位置是合適的,因為它會根據Message要處理的時間點進行排序,從它的插入操作也可以了解到MessageQueue采用了鏈表。

由于next方法和enqueueMessage方法的源碼過長,下面只貼出enqueueMessage排序Message的源碼:

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

關于阻塞但不會卡住主線程的問題在下一小節會提到。

Looper:從MessageQueue中獲取當前需要處理的消息,并提交給Handler處理

關于Looper在前面也講述了一部分,現在只剩下loop方法了,很重要。在它的內部也開啟了一個無限循環。

for無限循環中,有一句表明了會阻塞:

Message msg = queue.next(); // might block

導致它阻塞的原因在MessageQueue.next方法。當消息隊列退出或正在退出時,loop方法會結束,也就是跳出無限循環。

if (msg == null) {
   // No message indicates that the message queue is quitting.
   return;
}

在這個循環里還有一句需要注意的:

msg.target.dispatchMessage(msg);

意思時交給Handler處理這個Message。至此,整個流程就分析完了。

面試的時候可能會遇到:為什么loop方法會阻塞主線程但不會卡住呢?以下的文章也許可以解答你心中的疑問:

異步任務

  • 邏輯上:以多線程的方式完成的功能需求
  • API上:指AsyncTask

AsyncTask

  • 在沒有AsyncTask之前,我們用Handler+Thread就可以實現異步任務的功能需求
  • AsyncTask是針對HandlerThread的封裝,使用它編碼更加簡潔,更加高效
  • AsyncTask封裝了ThreadPool,比直接使用Thread效率要高

相關API

  • AsyncTack<Params,Progress,Ressult>
    • Params啟動任務執行的輸入參數,比如HTTP請求的URL
    • Progress后臺任務執行的百分比
    • Result后臺執行任務最終返回的結果,比如String
  • execute(Params... params):啟動任務,開始任務的執行流程
  • onPreExcute():在分線程工作開始之前在UIThread中執行,一般用來顯示提示視圖5
  • doInBackground(Params... params):在workerThread中執行,完成任務的主要工作,通常需要較長的時間
  • onPostExecute(Result result):在doInBackground執行完后再UIThread中執行,一般用來更新界面
  • publishProgress(Progress... values):在分線程中發布當前進度
  • onProgressUpdate(Progress... values):在主線程中更新進度

AsyncTask在具體的使用過程中也是有一些條件限制的,主要有以下幾種(摘自《Android開發藝術探索》):

  • 1、AsyncTask的類必須在主線程中加載,這就意味著第一次訪問AsyncTask必須發生在主線程,當然這個過程在Android 4.1及以上版本中已經被系統自動完成。在Android 5.0的源碼中,可以查看ActivityThreadmain方法,它會調用AsyncTaskinit方法,這就滿足了AsyncTask的類必須在主線程中進行加載這個條件了。
  • 2、AsyncTask的對象必須在主線程中創建。
  • 3、execute方法必須在UI線程調用。
  • 4、不要再程序中直接調用onPreExecuteonPostExecutedoInBackgroundonProgressUpdate方法
  • 5、一個AsyncTask對象只能執行一次,即只能調用一次execute方法,否則會報運行時異常
  • 6、在Android 1.6之前,AsyncTask是串行執行任務的,Android 1.6的時候AsyncTask開始采用線程池里處理并行任務,但是從Android 3.0開始,為了避免AsyncTask所帶來的并發錯誤,AsyncTask又采用一個線程來串行執行任務。盡管如此,在Android 3.0以及后續的版本中,我們仍然可以通過AsyncTaskexecuteOnExecutor方法來并行地執行任務。

總結

文章以Handler的創建過程為參照,簡單介紹了Handler的原理和源碼。文章末尾對AsyncTask進行了簡單的介紹。讀者有空可以讀一讀《Android開發藝術探索》的第10章和第11章。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,119評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,382評論 3 415
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,038評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,853評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,616評論 6 408
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,112評論 1 323
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,192評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,355評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,869評論 1 334
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,727評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,928評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,467評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,165評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,570評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,813評論 1 282
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,585評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,892評論 2 372

推薦閱讀更多精彩內容