Handler、AsyncTask 有啥區(qū)別和注意事項(xiàng)?

本文出自 “愛碼士” 簡書博客,轉(zhuǎn)載或引用請注明出處。

AsyncTask實(shí)現(xiàn)的原理,和適用的優(yōu)缺點(diǎn)

AsyncTask,是android提供的輕量級的異步類,可以直接繼承AsyncTask,在類中實(shí)現(xiàn)異步操作,并提供接口反饋當(dāng)前異步執(zhí)行的程度(可以通過接口實(shí)現(xiàn)UI進(jìn)度更新),最后反饋執(zhí)行的結(jié)果給UI主線程.

使用的優(yōu)點(diǎn):
簡單,快捷,過程可控
使用的缺點(diǎn):
在使用多個(gè)異步操作和并需要進(jìn)行Ui變更時(shí),就變得復(fù)雜起來.
最大并發(fā)數(shù)不超過5

Handler異步實(shí)現(xiàn)的原理和適用的優(yōu)缺點(diǎn)(原理分析在下方)

在Handler 異步實(shí)現(xiàn)時(shí),涉及到 Handler, Looper, Message,Thread四個(gè)對象,實(shí)現(xiàn)異步的流程是主線程啟動Thread(子線程)àthread(子線程)運(yùn)行并生成Message-àLooper獲取Message并傳遞給HandleràHandler逐個(gè)獲取Looper中的Message,并進(jìn)行UI變更。

使用的優(yōu)點(diǎn):
結(jié)構(gòu)清晰,功能定義明確
對于多個(gè)后臺任務(wù)時(shí),簡單,清晰
使用的缺點(diǎn):
在單個(gè)后臺異步處理時(shí),顯得代碼過多,結(jié)構(gòu)過于復(fù)雜(相對性)

AsyncTask介紹

AsyncTask比Handler更輕量級一些,適用于簡單的異步處理。

首先明確Android之所以有Handler和AsyncTask,都是為了不阻塞主線程(UI線程),且UI的更新只能在主線程中完成,因此異步處理是不可避免的。

Android為了降低這個(gè)開發(fā)難度,提供了AsyncTask。AsyncTask就是一個(gè)封裝過的后臺任務(wù)類,顧名思義就是異步任務(wù)。

AsyncTask直接繼承于Object類,位置為android.os.AsyncTask。要使用AsyncTask工作我們要提供三個(gè)泛型參數(shù),并重載幾個(gè)方法(至少重載一個(gè))。

AsyncTask定義了三種泛型類型 Params,Progress和Result。

Params 啟動任務(wù)執(zhí)行的輸入?yún)?shù),比如HTTP請求的URL。

Progress 后臺任務(wù)執(zhí)行的百分比。

Result 后臺執(zhí)行任務(wù)最終返回的結(jié)果,比如String。

使用過AsyncTask 的同學(xué)都知道一個(gè)異步加載數(shù)據(jù)最少要重寫以下這兩個(gè)方法:

doInBackground(Params…) 后臺執(zhí)行,比較耗時(shí)的操作都可以放在這里。注意這里不能直接操作UI。此方法在后臺線程執(zhí)行,完成任務(wù)的主要工作,通常需要較長的時(shí)間。在執(zhí)行過程中可以調(diào)用publicProgress(Progress…)來更新任務(wù)的進(jìn)度。

onPostExecute(Result) 相當(dāng)于Handler 處理UI的方式,在這里面可以使用在doInBackground 得到的結(jié)果處理操作UI。 此方法在主線程執(zhí)行,任務(wù)執(zhí)行的結(jié)果作為此方法的參數(shù)返回

有必要的話你還得重寫以下這三個(gè)方法,但不是必須的:

onProgressUpdate(Progress…) 可以使用進(jìn)度條增加用戶體驗(yàn)度。 此方法在主線程執(zhí)行,用于顯示任務(wù)執(zhí)行的進(jìn)度。

onPreExecute() 這里是最終用戶調(diào)用Excute時(shí)的接口,當(dāng)任務(wù)執(zhí)行之前開始調(diào)用此方法,可以在這里顯示進(jìn)度對話框。

onCancelled() 用戶調(diào)用取消時(shí),要做的操作

使用AsyncTask類,以下是幾條必須遵守的準(zhǔn)則:

Task的實(shí)例必須在UI thread中創(chuàng)建;

execute方法必須在UI thread中調(diào)用;

不要手動的調(diào)用onPreExecute(), onPostExecute(Result),doInBackground(Params...), onProgressUpdate(Progress...)這幾個(gè)方法;

該task只能被執(zhí)行一次,否則多次調(diào)用時(shí)將會出現(xiàn)異常;

Handler 異步消息處理機(jī)制原理解析

1、概述

Handler 、 Looper 、Message 這三者都與Android異步消息處理線程相關(guān)的概念。那么什么叫異步消息處理線程呢?
異步消息處理線程啟動后會進(jìn)入一個(gè)無限的循環(huán)體之中,每循環(huán)一次,從其內(nèi)部的消息隊(duì)列中取出一個(gè)消息,然后回調(diào)相應(yīng)的消息處理函數(shù),執(zhí)行完成一個(gè)消息后則繼續(xù)循環(huán)。若消息隊(duì)列為空,線程則會阻塞等待。

2、源碼解析
1、Looper

對于Looper主要是prepare()和loop()兩個(gè)方法。
首先看prepare()方法

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

/**
 * UI線程調(diào)用
 */
public static void prepareMainLooper() {
        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");
        }
        sThreadLocal.set(new Looper(quitAllowed));
    }

sThreadLocal是一個(gè)ThreadLocal對象,可以在一個(gè)線程中存儲變量??梢钥吹?,源碼中將一個(gè)Looper的實(shí)例放入了ThreadLocal,并且判斷了sThreadLocal是否為null,否則拋出異常。這也就說明了Looper.prepare()方法不能被調(diào)用兩次,同時(shí)也保證了一個(gè)線程中只有一個(gè)Looper實(shí)例~相信有些哥們一定遇到這個(gè)錯誤。

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

下面看Looper的構(gòu)造方法:

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

在構(gòu)造方法中,創(chuàng)建了一個(gè)MessageQueue(消息隊(duì)列)。
然后我們看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
            final Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }

            final long traceTag = me.mTraceTag;
            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            try {
                msg.target.dispatchMessage(msg);
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }

            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();
        }
    }
public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }

final Looper me = myLooper();\\方法直接返回了sThreadLocal存儲的Looper實(shí)例,如果me為null則拋出異常,也就是說looper方法必須在prepare方法之后運(yùn)行。

final MessageQueue queue = me.mQueue;\\拿到該looper實(shí)例中的mQueue(消息隊(duì)列)。

for (;;) {......}\\進(jìn)入了我們所說的無限循環(huán)。
Message msg = queue.next(); //取出一條消息,如果沒有消息則阻塞。

使用調(diào)用 msg.target.dispatchMessage(msg);把消息交給msg的target的dispatchMessage方法去處理。Msg的target是什么呢?其實(shí)就是handler對象,下面會進(jìn)行分析。
msg.recycleUnchecked();\\釋放消息占據(jù)的資源。

Looper主要作用:
1、 與當(dāng)前線程綁定,保證一個(gè)線程只會有一個(gè)Looper實(shí)例,同時(shí)一個(gè)Looper實(shí)例也只有一個(gè)MessageQueue。
2、 loop()方法,不斷從MessageQueue中去取消息,交給消息的target屬性的dispatchMessage去處理。
好了,我們的異步消息處理線程已經(jīng)有了消息隊(duì)列(MessageQueue),也有了在無限循環(huán)體中取出消息的哥們,現(xiàn)在缺的就是發(fā)送消息的對象了,于是乎:Handler登場了。

2、Handler

使用Handler之前,我們都是初始化一個(gè)實(shí)例,比如用于更新UI線程,我們會在聲明的時(shí)候直接初始化,或者在onCreate中初始化Handler實(shí)例。所以我們首先看Handler的構(gòu)造方法,看其如何與MessageQueue聯(lián)系上的,它在子線程中發(fā)送的消息(一般發(fā)送消息都在非UI線程)怎么發(fā)送到MessageQueue中的。

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

通過Looper.myLooper()獲取了當(dāng)前線程保存的Looper實(shí)例mLooper,然后又獲取了這個(gè)Looper實(shí)例中保存的MessageQueue(消息隊(duì)列)-->mQueue = mLooper.mQueue;這樣就保證了handler的實(shí)例與我們Looper實(shí)例中MessageQueue關(guān)聯(lián)上了。

然后看我們最常用的sendMessage方法

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

enqueueMessage中首先為meg.target賦值為this,【如果大家還記得Looper的loop方法會取出每個(gè)msg然后交給msg,target.dispatchMessage(msg)去處理消息】,也就是把當(dāng)前的handler作為msg的target屬性。最終會調(diào)用queue的enqueueMessage的方法,也就是說handler發(fā)出的消息,最終會保存到消息隊(duì)列中去。

現(xiàn)在已經(jīng)很清楚了Looper會調(diào)用prepare()和loop()方法,在當(dāng)前執(zhí)行的線程中保存一個(gè)Looper實(shí)例,這個(gè)實(shí)例會保存一個(gè)MessageQueue對象,然后當(dāng)前線程進(jìn)入一個(gè)無限循環(huán)中去,不斷從MessageQueue中讀取Handler發(fā)來的消息。然后再回調(diào)創(chuàng)建這個(gè)消息的handler中的dispathMessage方法,下面我們趕快去看一看這個(gè)方法:

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

可以看到,調(diào)用了handleMessage方法,下面我們?nèi)タ催@個(gè)方法:

public void handleMessage(Message msg) {
    }

可以看到這是一個(gè)空方法,為什么呢,因?yàn)橄⒌淖罱K回調(diào)是由我們控制的,我們在創(chuàng)建handler的時(shí)候都是復(fù)寫handleMessage方法,然后根據(jù)msg.what進(jìn)行消息處理。

例如:

private Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            
        }
    };

到此,這個(gè)流程已經(jīng)解釋完畢,讓我們首先總結(jié)一下
1、首先Looper.prepare()在本線程中保存一個(gè)Looper實(shí)例,然后該實(shí)例中保存一個(gè)MessageQueue對象;因?yàn)長ooper.prepare()在一個(gè)線程中只能調(diào)用一次,所以MessageQueue在一個(gè)線程中只會存在一個(gè)。
2、Looper.loop()會讓當(dāng)前線程進(jìn)入一個(gè)無限循環(huán),不端從MessageQueue的實(shí)例中讀取消息,然后回調(diào)msg.target.dispatchMessage(msg)方法。
3、Handler的構(gòu)造方法,會首先得到當(dāng)前線程中保存的Looper實(shí)例,進(jìn)而與Looper實(shí)例中的MessageQueue想關(guān)聯(lián)。
4、Handler的sendMessage方法,會給msg的target賦值為handler自身,然后加入MessageQueue中。
5、在構(gòu)造Handler實(shí)例時(shí),我們會重寫handleMessage方法,也就是msg.target.dispatchMessage(msg)最終調(diào)用的方法。
好了,總結(jié)完成,大家可能還會問,那么在Activity中,我們并沒有顯示的調(diào)用Looper.prepare()和Looper.loop()方法,為啥Handler可以成功創(chuàng)建呢,這是因?yàn)樵贏ctivity的啟動代碼中,已經(jīng)在當(dāng)前UI線程調(diào)用了Looper.prepare()和Looper.loop()方法。

參考:

《安卓開發(fā)藝術(shù)探索》
Android異步消息處理機(jī)制完全解析,帶你從源碼的角度徹底理解

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容