【面試題】handler內(nèi)存泄露的根本原因是?

This Handler class should be static or leaks might occur (anonymous android.os.Handler) less... (Ctrl+F1)
Since this Handler is declared as an inner class, it may prevent the outer class from being garbage collected. If the Handler is using a Looper or MessageQueue for a thread other than the main thread, then there is no issue. If the Handler is using the Looper or MessageQueue of the main thread, you need to fix your Handler declaration, as follows: Declare the Handler as a static class; In the outer class, instantiate a WeakReference to the outer class and pass this object to your Handler when you instantiate the Handler; Make all references to members of the outer class using the WeakReference object.

簡單翻譯如下:

由于handler定義為內(nèi)部類,可能會阻止GC。如果handler的Looper或MessageQueue 非主線程,那么沒有問題。如果handler的Looper或MessageQueue 在主線程,那么需要按如下定義:定義handler為靜態(tài)內(nèi)部類,當(dāng)你實(shí)例化handler的時(shí)候,傳入一個(gè)外部類的弱引用,以便通過弱引用使用外部類的所有成員。

handler導(dǎo)致activity內(nèi)存泄露的原因:

handler發(fā)送消息在當(dāng)前handler的消息隊(duì)列中,如果這個(gè)時(shí)候activity finish(),
那么消息隊(duì)列里的消息依舊會由handler進(jìn)行處理,如果此時(shí)handler聲明為內(nèi)部類(非靜態(tài)),內(nèi)部類持有外部類的實(shí)例引用,那么就會導(dǎo)致activity無法回收,所以導(dǎo)致activity泄漏內(nèi)存

為何handler要定義為static?

因?yàn)殪o態(tài)內(nèi)部類不持有外部類的引用,所以使用靜態(tài)的handler不會導(dǎo)致activity的泄露

為何handler要定義為static的同時(shí),還要用WeakReference 包裹外部類的對象?

以便通過弱引用使用外部類的所有成員。

避免handle內(nèi)存泄露的辦法
  • 1.使用static 修飾的handler,使用弱引用activity對象,因?yàn)橐褂?code>activity對象中的成員
  • 2.單獨(dú)定義handler,同樣可以弱引用activity
  • 3.使用內(nèi)部類的handler,在onDestroy方法中removeCallbacksAndMessages
最后編輯于
?著作權(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)容