我知道,如果您直接初始化Handler
并在Activity
中使用它,则会泄漏Context
(由Alex Lockwood提供),例如
public class SampleActivity extends Activity {
private final Handler mLeakyHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
/* ... */
}
}
}
所以我使用了以下方法
private static class StaticHandler extends Handler {
private final WeakReference<SampleActivity> mSampleAct;
private StaticHandler(SampleActivity act) {
mSampleAct = new WeakReference<SampleActivity>(
act);
}
}
然后我将其初始化为
public class SampleActivity extends Activity {
private Handler myHandler = new StaticHandler(this) {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
processTask(msg.obj);
}
};
}
我想知道我的Handler
即myHandler是否仍会泄漏Context
,我怎么能确定它不会泄漏?
答案 0 :(得分:2)
使用WeakReference
绝对是避免内存泄漏的明智方法。代码在上下文中看起来不错,但确保它不会泄漏内存的最佳方法是使用DDMS内存分析器。阅读更多:Memory Analyzer Tool in android?