轉自android handler的警告Handler Class Should be Static or Leaks Occur
在使用Handler更新UI的時候,我是這樣寫的:
public class SampleActivity extends Activity {
private final Handler mLeakyHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO
}
}
}
看起來很正常的,但是 Android Lint 卻給出了警告:
This Handler class should be static or leaks might occur
意思是說:這個Handler必須是static的,否則就會引發內存泄露。
其實,對於這個問題,Android Framework 的工程師 Romain Guy 早已經在Google論壇上做出過解釋,並且給出了他的建議寫法:
I wrote that debugging code because of a couple of memory leaks I
found in the Android codebase. Like you said, a Message has a
reference to the Handler which, when it’s inner and non-static, has a
reference to the outer this (an Activity for instance.) If the Message
lives in the queue for a long time, which happens fairly easily when
posting a delayed message for instance, you keep a reference to the
Activity and “leak” all the views and resources. It gets even worse
when you obtain a Message and don’t post it right away but keep it
somewhere (for instance in a static structure) for later use.
他的建議寫法是:
class OuterClass {
class InnerClass {
private final WeakReference<OuterClass> mTarget;
InnerClass(OuterClass target) {
mTarget = new WeakReference<OuterClass>(target);
}
void doSomething() {
OuterClass target = mTarget.get();
if (target != null) {
target.do();
}
}
}
下面,我們進一步解釋一下:
- Android App啓動的時候,Android Framework 爲主線程創建一個Looper對象,這個Looper對象將貫穿這個App的整個生命週期,它實現了一個消息隊列(Message Queue),並且開啓一個循環來處理Message對象。而Framework的主要事件都包含着內部Message對象,當這些事件被觸發的時候,Message對象會被加到消息隊列中執行。
- 當一個Handler被實例化時(如上面那樣),它將和主線程Looper對象的消息隊列相關聯,被推到消息隊列中的Message對象將持有一個Handler的引用以便於當Looper處理到這個Message的時候,Framework執行Handler的handleMessage(Message)方法。
- 在 Java 語言中,非靜態匿名內部類將持有一個對外部類的隱式引用,而靜態內部類則不會。
到底內存泄露是在哪裏發生的呢?以下面代碼爲例:
public class SampleActivity extends Activity {
private final Handler mLeakyHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// ...
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Post a message and delay its execution for 10 minutes.
mLeakyHandler.postDelayed(new Runnable() {
@Override
public void run() { }
}, 60 * 10 * 1000);
// Go back to the previous Activity.
finish();
}
}
當Activity被finish()掉,Message將存在於消息隊列中長達10分鐘的時間纔會被執行到。這個Message持有一個對Handler的引用,Handler也會持有一個對於外部類(SampleActivity)的隱式引用,這些引用在Message被執行前將一直保持,這樣會保證Activity的上下文不被垃圾回收機制回收,同時也會泄露應用程序的資源(views and resources)。
爲解決這個問題,下面這段代碼中的Handler則是一個靜態匿名內部類。靜態匿名內部類不會持有一個對外部類的隱式引用,因此Activity將不會被泄露。如果你需要在Handler中調用外部Activity的方法,就讓Handler持有一個對Activity的WeakReference,這樣就不會泄露Activity的上下文了,如下所示:
public class SampleActivity extends Activity {
/**
* Instances of static inner classes do not hold an implicit
* reference to their outer class.
*/
private static class MyHandler extends Handler {
private final WeakReference<SampleActivity> mActivity;
public MyHandler(SampleActivity activity) {
mActivity = new WeakReference<SampleActivity>(activity);
}
@Override
public void handleMessage(Message msg) {
SampleActivity activity = mActivity.get();
if (activity != null) {
// ...
}
}
}
private final MyHandler mHandler = new MyHandler(this);
/**
* Instances of anonymous classes do not hold an implicit
* reference to their outer class when they are "static".
*/
private static final Runnable sRunnable = new Runnable() {
@Override
public void run() { }
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Post a message and delay its execution for 10 minutes.
mHandler.postDelayed(sRunnable, 60 * 10 * 1000);
// Go back to the previous Activity.
finish();
}
}
總結:
在實際開發中,如果內部類的生命週期和Activity的生命週期不一致(比如上面那種,Activity finish()之後要等10分鐘,內部類的實例纔會執行),則在Activity中要避免使用非靜態的內部類,這種情況,就使用一個靜態內部類,同時持有一個對Activity的WeakReference。