Android Handler消息機制使用和原理

前言:奮鬥是這麼個過程,當時不覺累,事後不會悔。走一段再回頭,會發現一個更強的自己,宛如新生!

一、概述

在Android開發過程中,我們常常會將一些耗時的操作放在子線程中執行(work thread),然後將執行的結果告訴UI線程(main thread)也叫主線程,因爲UI的更新只能在Main Thread中執行,那麼這裏就涉及怎麼將數據傳遞給主線程(main thread),需要藉助安卓的消息機制。

Android爲我們提供了消息傳遞機制——Handler,來幫助我們將數據從子線程傳遞給主線程,其實,當我們熟悉Handler的原理之後,Handler不僅能實現子線程傳遞數據給主線程,還能實現任意兩個線程之間的數據傳遞。

主線程:也叫UI線程,或者Activity Thread,用於運行四大組件和用戶的交互,用於處理各種和界面相關的事情,Activity Thread管理應用進程的主線程的執行。

子線程:用於執行耗時操作,比如I/O操作或者網絡請求,安卓3.0以後要求訪問網絡必須在子線程中執行,更新UI的操作必須交給主線程,子線程不允許更新UI。

1.什麼是消息機制?

不同線程之間的通信。

2.什麼是安卓消息機制?

Handler運行機制。

3.安卓消息機制有什麼用?

線程之間通信,主要是避免ANR(Application Not Responding),一旦出現ANR,程序就會崩潰。

4.什麼情況下出現ANR?

  • Activity裏面的響應超過5秒;
  • Broadcast在處理的時間超過10秒;
  • Service處理時間超過20秒;

造成上面三種情況的原因很多,網絡請求,大文件的讀取,耗時的計算等都會引發ANR。

5.如何避免ANR?

主線程不能執行耗時操作,子線程不行更新UI,那麼把耗時操作放到子線程中執行,通過Handler消息機制通知主線程更新UI。

6.爲什麼子線程不能更新UI?

在Andorid系統中出於性能優化的考慮,UI操作不是線程安全的,這意味着多個線程併發操作ui控件可能會導致線程安全問題,如果對UI控件加上上鎖機制,會使控件變得複雜低效,也會阻塞某些進程的執行。爲了解決這個問題,Android規定只允許UI線程(主線程)修改Activity中的UI組件,但是實際上,有部分UI需要在子線程中控制邏輯,因此子線程需要通過Handler通知主線程修改UI,實現線程間通信。最根本就是爲了解決多線程併發的問題。

二、Handler的使用

首先來看下Handler最常規的使用模式(源碼地址在文章最後給出)

 private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    mTextView.setText((String) msg.obj);
                    Toast.makeText(MainActivity.this, (String) msg.obj, Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

     /**
     * 子線程通知主線程更新UI
     */
    private void sendMsgToMainThreadByWorkThread() {
        //創建子線程
        new Thread(new Runnable() {
            @Override
            public void run() {
                //獲取消息載體
                Message msg = Message.obtain();
                msg.what = 1;
                msg.obj = "子線程通知主線程更新UI";
                mHandler.sendMessage(msg);
            }
        }).start();
    }

通常我們在主線程中創建一個Handler,通過重寫handler的handleMessage(Message msg)方法,從參數Message中獲取傳遞過來的信息數據,子線程中通過obtain()獲取Message信息載體實例,最後通過sendMessage(msg)發送消息,我們來看看Message的幾個屬性:

  • Message.what                                     用來標識信息得int值,區分來自不同地方的信息來源
  • Message.obj                                        用來傳遞的實例化對象(信息數據)
  • Message.arg1/Message.arg2              Message初始定義的用來傳遞int類型值的兩個變量

Handler消息機制的處理過程:從Handler中通過obtainMessage()獲取消息對象Message,把數據封裝到Message消息對象中,通過handler的sendMessage()方法把消息push到MessageQueque中,Looper對象會輪詢MessageQueque隊列,把消息對象取出,再通過dispatchMessage分發給handler,通過回調實現handler的handleMessage方法處理消息。

這裏引出了handler機制的幾個關鍵對象,handler、Looper、MessageQueque、Message。

Handler:發送和處理消息,它把消息發送給Looper管理的MessageQueque,並負責處理Looper發送給他的消息

Looper:消息隊列的處理者(輪詢隊列),每個線程只有一個Looper,負責管理MessageQueque,會不斷地從Message中取出消息,分發給Handler

Message:消息對象(存儲數據),它封裝了任務攜帶的額外信息和處理該任務的 Handler 引用。

MessageQueque:消息隊列,由Looper管理,採用先進先出的方法管理Message(存放數據結構,內部使用鏈表數據結構存儲多個消息對象,最大長度爲50,目的是爲了重用message對象,減少Message對象的創建,造成產生大量的垃圾對象)

三、任意線程和原理

我們來看看任意兩個子線程間調用handler:

   private Handler handler;

    /**
     * 任意線程間的通信
     */
    private void handlerWorkThread() {
        new Thread(new Runnable() {
            @Override
            public void run() {
//                Looper.prepare();//不寫此代碼會報異常
                // 注意:一定要在兩個方法之間創建綁定當前Looper的Handler對象,
                // 否則一旦線程開始進入死循環就沒法再創建Handler處理Message了
                handler = new Handler() {
                    @Override
                    public void handleMessage(final Message msg) {
                        super.handleMessage(msg);
                        switch (msg.what) {
                            case 2:
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        mTextView.setText((String) msg.obj);
                                        Toast.makeText(MainActivity.this, (String) msg.obj, Toast.LENGTH_SHORT).show();
                                        System.out.println("Str=============================" + msg.obj);
                                    }
                                });

                                break;
                        }
                    }
                };
                //開始循壞處理消息隊列
//                Looper.loop();//不寫此代碼會無法接受數據
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
   //不需要直接new Message,通過handler.obtainMessage()獲取Message實例,底層直接是
                //調用了Message.obtain()方法,實現消息的複用,Message內部維護有數據緩存池
                Message message = handler.obtainMessage();
                message.what = 2;
                message.obj = "任意線程間的通信";
                handler.sendMessage(message);
            }
        }).start();
    }

從代碼中,我們創建了兩個子線程,在第一個子線程中創建handler,並且實現handlerMessage()方法,在第二個子線程中創建消息實例Message,封裝數據並通過handler發送。將上面的代碼跑起來,但是報異常了:

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
No Looper; 

注意:一個線程創建handler時是需要先創建Looper的,而且每個線程只需要創建一個Looper,否則會報錯:

RuntimeException: Only one Looper may be created per thread。

其實,子線程中如果使用handler需要手動調用Looper.prepare()Looper.loop(),不調用Looper.prepare()會報上面兩個異常,不調用Looper.loop()則會handler收不到消息,我們來看看爲什麼子線程中不創建Looper會報錯,在new Handler()爲什麼會報錯,

3.1 Handler

 //可以看到Looper爲空的時候才跑出該異常
 public Handler(Callback callback, boolean async) {
        //關聯到當前線程的Looper
        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread " + Thread.currentThread()
                        + " that has not called Looper.prepare()");
        }
        //持有當前Looper中消息隊列的引用
        mQueue = mLooper.mQueue;
        mCallback = callback;
        //設置消息是否異步
        mAsynchronous = async;
    }

 //我們來看看Looper.prepare()都幹了什麼
 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));
}

//可以看出在當前Thread創建了一個Looper,ThreadLocal主要用於維護本地線程的變量,而Looper的構造函
//數又爲我們創建了一個消息隊列MessageQueue
  private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

但是爲什麼主線程中不需要Looper.prepare()Looper.loop(),其實是因爲App初始化的時候都會執行ActivityThread的main方法,所以UI線程能直接使用Handler,我們可看一看裏面做了什麼操作:

3.2 ActivityThread-Main

  public static void main(String[] args) {

        Looper.prepareMainLooper();

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

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

從中可以看到在創建主線程的時候android已經幫我們調用了Looper.prepareMainLooper()Looper.loop()方法,所以我們能再主線程中直接創建Handler使用。

我們來看看Handler發送消息的過程,有多個方法實現這個功能,如:post()、postAtTime()、postDelayed()、sendMessage()、sendMessageAtTime()、sendMessageDelayed()等等:

3.3 handler發送消息

  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) {
     // 核心代碼,sendMessage一路調用到此,讓Message持有當前Handler的引用
    // 當消息被Looper線程輪詢到時,可以通過target回調Handler的handleMessage方法
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
     //將message加入MessageQueque中,並且根據消息延遲排序
        return queue.enqueueMessage(msg, uptimeMillis);
    }

最後一段是發送消息的核心代碼,handler發送消息最終會走到這裏,讓Message持有當前Handler的引用,當消息被Looper輪詢到時,可以通過target回調handler的handleMessage()方法,sendMessage()的關鍵在於queue.enqueueMessage(msg, uptimeMillis),其內部調用了MessageQueque的enqueueMessage()方法。

3.4 MessageQueque

enqueueMessage()

 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;
            if (p == null || when == 0 || when < p.when) {
            //隊列無消息或者插入消息的執行時間爲0(強制插入隊頭)亦或者插入消息的執行時間先於隊頭時間,這三總情況插入消息爲新隊頭,如果隊列被阻塞,則會被喚醒。
                // 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;
    }

從代碼可以看出,Message存放到MessageQueque中時,是將Message存放到Message.next中,形成一個鏈式的列表,同時也保證了Message列表的時序性,MessageQueque.next()方法從消息隊列中取出一個需要處理的消息,如果沒有消息或者消息還沒到時該隊列會阻塞,等待消息通過MessageQueque.enqueueMessage()進入消息隊列後喚醒線程。

MessageQueque.next()


    Message next() {
       ······
        final long ptr = mPtr;
        if (ptr == 0) {
            return null;
        }

        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        int nextPollTimeoutMillis = 0;
        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }

            //通過Native層的MessageQueque阻塞nextPollTimeoutMillis毫秒時間
            nativePollOnce(ptr, nextPollTimeoutMillis);

            synchronized (this) {
                //嘗試檢索下一條消息,如果找到則返回該消息
                final long now = SystemClock.uptimeMillis();
                Message prevMsg = null;
                Message msg = mMessages;
                if (msg != null && msg.target == null) {
                    //被target爲null的消息屏障阻塞,查找隊列中的下一個異步消息
                    do {
                        prevMsg = msg;
                        msg = msg.next;
                    } while (msg != null && !msg.isAsynchronous());
                }
                if (msg != null) {
                    if (now < msg.when) {
                        //下一個消息尚未就緒,設置超時以在準備就緒時喚醒
                        nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                    } else {
                        //從隊列中獲取一個重要執行的消息
                        mBlocked = false;
                        if (prevMsg != null) {
                            prevMsg.next = msg.next;
                        } else {
                            mMessages = msg.next;
                        }
                        msg.next = null;
                        if (DEBUG) Log.v(TAG, "Returning message: " + msg);
                        msg.markInUse();
                        return msg;
                    }
                } else {
                    //隊列沒有消息,一值被阻塞,等待喚醒
                    nextPollTimeoutMillis = -1;
                }

                // Process the quit message now that all pending messages have been handled.
                if (mQuitting) {
                    dispose();
                    return null;
                }

                // If first time idle, then get the number of idlers to run.
                // Idle handles only run if the queue is empty or if the first message
                // in the queue (possibly a barrier) is due to be handled in the future.
                if (pendingIdleHandlerCount < 0
                        && (mMessages == null || now < mMessages.when)) {
                    pendingIdleHandlerCount = mIdleHandlers.size();
                }
                if (pendingIdleHandlerCount <= 0) {
                    // No idle handlers to run.  Loop and wait some more.
                    mBlocked = true;
                    continue;
                }

                if (mPendingIdleHandlers == null) {
                    mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
                }
                mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
            }

            // Run the idle handlers.
            // We only ever reach this code block during the first iteration.
            for (int i = 0; i < pendingIdleHandlerCount; i++) {
                final IdleHandler idler = mPendingIdleHandlers[i];
                mPendingIdleHandlers[i] = null; // release the reference to the handler

                boolean keep = false;
                try {
                    keep = idler.queueIdle();
                } catch (Throwable t) {
                    Log.wtf(TAG, "IdleHandler threw exception", t);
                }

                if (!keep) {
                    synchronized (this) {
                        mIdleHandlers.remove(idler);
                    }
                }
            }

            // Reset the idle handler count to 0 so we do not run them again.
            pendingIdleHandlerCount = 0;

            // While calling an idle handler, a new message could have been delivered
            // so go back and look again for a pending message without waiting.
            nextPollTimeoutMillis = 0;
        }
    }

Message的發送實際是放入Handler對應線程的MessageQueque中,那麼Message是如何被取出來的呢?在前面的例子也講到,如果不調用Looper.loop()的話,handler是接收不到消息的,我們來看看loop()方法:

3.5 Looper

Looper.loop()

   /**
     * Run the message queue in this thread. Be sure to call
     * {@link #quit()} to end the loop.
     */
    public static void loop() {
        //得到當前線程的Looper對象
        final Looper me = myLooper();
        //調用Looper.prepare()之前是不能調用該方法的,不然又拋異常了
        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();

        // Allow overriding a threshold with a system prop. e.g.
        // adb shell 'setprop log.looper.1000.main.slow 1 && stop && start'
        final int thresholdOverride =
                SystemProperties.getInt("log.looper."
                        + Process.myUid() + "."
                        + Thread.currentThread().getName()
                        + ".slow", 0);

        boolean slowDeliveryDetected = false;

        //開始循環
        for (;;) {
            //從消息隊列中獲取一下message,該方法可以被阻塞
            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 dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
            final long dispatchEnd;
            try {
                //將message推送到Message中的target處理,此處的target就是發送該Message的handler對象
                msg.target.dispatchMessage(msg);
                dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            ·······
            if (logSlowDispatch) {
                showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", msg);
            }

            if (logging != null) {
                logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
            }
            ·······
            //回收message,這樣通過Message.obtain()複用
            msg.recycleUnchecked();
        }
    }

該方法啓動線程的循環模式,從Looper的MessageQueque中不斷提取Message,再交給Handler處理任務,最後回收Message複用。我們再回頭看下Looper.prepare()方法:

Looper.prepare()

public final class Looper {
 
    //每個線程僅包含一個Looper對象,定義爲一個本地存儲對象
    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
    private static Looper sMainLooper;  // guarded by Looper.class

    //每一個Looper維護一個唯一的消息隊列
    final MessageQueue mQueue;
    final Thread mThread;

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

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

    //該方法會在調用線程的TLS中創建Looper對象,爲線程私有
    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));
    }
}

該方法在線程中將Looper定義爲ThreadLocal對象,使得Looper成爲線程的私有對象,一個線程最多僅有一個Looper,並在這Looper對象中維護一個消息隊列MessageQueque和持有當前線程的引用,因此MessageQueque也是線程私有。

從上面的Looper.loop()中得知,Looper通過MessageQueque中取出消息Message,通過Message的Target(就是handler)調用dispatchMessage()去分發消息,繼續分析Message的分發:

3.6 handler-handleMessage()

 public interface Callback {
        public boolean handleMessage(Message msg);
    }

    /**
     * Handle system messages here.
     */
    //處理消息,此方法由Looper的loop方法調用
    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            //處理Runnable類消息
            handleCallback(msg);
        } else {
            //這種方法允許Activity等實現Handler.Callback接口,避免自己定義handler重寫HandleMessage()方法
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            //根據handler子類實現回調方法處理消息
            handleMessage(msg);
        }
    }

 //處理Runnable類消息方法
 private static void handleCallback(Message message) {
        //直接調用Message中封裝的Runnable的run方法
        message.callback.run();
    }

  //handler子類實現回調的方法
  public void handleMessage(Message msg) {
    }

如果設置了callback(Runnable對象),則會直接調用handleCallback方法,如果msg.callback==null,會直接調用我們的mCallback.handleMessage(msg),即handler的handlerMessage方法。由於Handler對象是在主線程中創建的,所以handler的handlerMessage方法的執行也會在主線程中。

任何持有handler引用的其他線程都可發送消息,消息都發送到Handler內部關聯的MessageQueque中,而handler是在Looper線程中創建的(Looper.praprepare()之後,Looper.loop()之前),所以handler是在其關聯的Looper線程中處理取得關聯消息的。

3.7 Message

在消息處理機制中,Message扮演的角色就是消息本身,它封裝了任務攜帶的額外消息和處理該任務的Handler引用。

Message雖然有public構造方法,但是還是建議用Message.obtain()從一個全局的消息池中得到空的Message對象,這樣有效的節省系統資源,Handler有一套obtain方法,其本質是調用Message的obtain方法,最終都是調用Message.obtain()

另外可以利用Message.what來區分消息類型,以處理不同的任務,在需要攜帶簡單的int類型額外消息時,可以優先使用Message.arg1和Message.arg2,這樣比bundle封裝消息更省資源。

源碼總結:

1、創建Handler實例,關聯Looper(非主線程還要調用looper.prepare(),handler所創建的線程需要維護一個唯一的Looper對象,一個線程最多僅有一個Looper,每個線程的Looper通過ThreadLocal來保證,並在這Looper對象中維護一個消息隊列MessageQueque和持有當前線程的引用)。

2、Handler通過sendMessage(Message msg)發送消息,sendMessage()其內部最終調用了MessageQueque的enqueueMessage()方法。將message時序性放入Handler對應線程的MessageQueque中。Message在MessageQueue不是通過一個列表來存儲的,而是將傳入的Message存入到了上一個Message的next中,在取出的時候通過頂部的Message就能按放入的順序依次取出Message

3、Looper.loop()啓動線程的循環模式,從Looper的MessageQueque中不斷提取Message,通過msg.target.dispatchMessage(msg)完成消息的發送,將message推送到Message中的target(handler)處理,再交給Handler處理任務,最後回收Message複用。

4、最後handler實現handlerMessage()方法接收處理數據。

圖片流程:

四、handler的使用注意事項

4.1 注意內存泄漏

使用Handler是用來線程間通信的,所以新開的線程會持有Handler的引用,如果在Activity中創建Handler並且是非靜態內部類的形式,就有可能導致內存泄漏。

1.因爲非靜態內部類會隱式持有外部類的引用,當其他線程持有該handler,如果線程沒有被銷燬,就會知道Activity一直被Handler持有引用而導致無法回收。

2.如果消息隊列MessageQueque中還有沒處理完的消息,Message中的target也是會持有Activity的引用,也會造成內存泄漏。

解決辦法:使用靜態內部類+弱引用

(1.)靜態內部類不會持有有外部了的引用,當使用外部類相關操作時,可以通過弱引用回去相關數據

   public static class ProtectHandler extends Handler {
        private WeakReference<Activity> mActivity;

        public ProtectHandler(Activity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Activity activity = mActivity.get();
            if (activity != null && !activity.isFinishing()) {
                //todo
            }
        }
    }

(2.)在外部類被銷燬時,將消息隊列清空,例如:在activity銷燬時清空MessageQueque.

  @Override
    protected void onDestroy() {
        //清空消息
        mHandler.removeCallbacksAndMessages(null);
        super.onDestroy();
    }

4.2 ThreadLocal是什麼?

ThreadLocal可以包裝一個對象,使其成爲線程私有的局部變量,通過ThreadLocal的get()和set()獲得的變量,不受其他線程影響。ThreadLocal實現了線程之間的數據隔離,同時提升了同一線程訪問變量的便利性。

至此,本文結束!

 

源碼地址:https://github.com/FollowExcellence/HandlerDemo

請尊重原創者版權,轉載請標明出處:https://mp.csdn.net/postedit/100524852 謝謝!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章