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