Android記憶體最佳化:Handler

來源:互聯網
上載者:User

Android記憶體最佳化:Handler

在避免記憶體泄露的文章中,Handler經常被提起,原因就是對象的強引用,比如一個Activity內部有一個Handler對象在運行

 

private Handler handler;handler = new Handler(){@Overridepublic void handleMessage(Message msg) {// TODO Auto-generated method stubsuper.handleMessage(msg);}};Message message = new Message();message.what = 1;handler.sendMessage(message);
當我們使用上面代碼建立一個Handler時,IDE就會給我提示

 

This Handler class should be static or leaks might occur (com.example.androidtest.MainActivity.2)
告訴我們,會產生記憶體泄露。

當Activity關閉時,Handler不一定處理完畢,但是Handler對Activity有參考關聯性,導致GC無法回收Activity對象,造成記憶體泄露。那麼Handler為什麼會這樣呢,那就看看它的實現吧。

在Handler對象中會隱式的引用到Activity,這就形成了強引用,也是造成記憶體泄露的原因。
Handler是用來處理訊息的,那麼就要有一個對象進行訊息的分發,這就是Looper
當進程啟動時,ActivityThread會建立一個Looper對象,Looper對象的研究,參考老羅的文章 http://blog.csdn.net/luoshengyang/article/details/6817933
    public static void prepareMainLooper() {//調用prepare建立Looper        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);        }//這裡new了一個Looper對象        sThreadLocal.set(new Looper(quitAllowed));    }//sThreadLocal是個靜態變數static final ThreadLocal sThreadLocal = new ThreadLocal();

Looper中有一個MessageQueue對象,儲存著訊息佇列
final MessageQueue mQueue;

當Handler發送訊息時,訊息會被加入到MessageQueue中,並且Message的target對象和Handler進行了綁定,這樣這個訊息也就對Activity進行了引用,只要這個訊息在,GC就無法回收已經關閉的Activity

handler.sendMessage發送訊息最終調用下面的方法,持有了Activity

 

    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) {//這裡就是,訊息持有了handler對象,handler持有Activity        msg.target = this;        if (mAsynchronous) {            msg.setAsynchronous(true);        }        return queue.enqueueMessage(msg, uptimeMillis);    }

 

 

當Handler建立時,會關聯到上面建立的Looper對象,這樣訊息機制就可以運轉起來了。
    public Handler(Callback callback, boolean async) {        if (FIND_POTENTIAL_LEAKS) {            final Class  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());            }        }//取出Looper        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;    }

知道了上面的原因,那麼為了避免記憶體泄露,我們可以採用以下方法,具體實現網上有很多文章,這裡不再羅列。
1、用static聲明handler,靜態類不會引用外部類
2、如果Handler中必須用到Activity,那就用WeakReference去引用
3、在Activity結束或暫停事件中,removeMessages或者removeCallbacksAndMessages將訊息佇列中的訊息移除(避免滿足上面兩條後,當Activity關閉了,但是Handler還未處理到,造成記憶體泄露)

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.