项目作者: NieQing

项目描述 :
Handler内存泄漏的处理方法
高级语言: Java
项目地址: git://github.com/NieQing/Handler-Memory-Leak.git
创建时间: 2018-03-21T02:43:08Z
项目社区:https://github.com/NieQing/Handler-Memory-Leak

开源协议:Apache License 2.0

下载


Handler-Memory-Leak

Handler内存泄漏的处理方法

过去 Android 使用 Handler 进行线程间通信来更新 UI ,但在 Android Studio 2.3.3 之后使用传统的写法 IDE 会提示:

  1. This Handler class should be static or leaks might occur.“

传统写法如下:

  1. public class MainActivity extends Activity {
  2. private final Handler handler = new Handler() {
  3. @Override
  4. public void handleMessage(Message msg) {
  5. // TODO
  6. }
  7. }
  8. }

Android Framework 的工程师 Romain Guy 在 Google 论坛上做出过解释:

  1. I wrote that debugging code because of a couple of memory leaks I
  2. found in the Android codebase. Like you said, a Message has a
  3. reference to the Handler which, when it's inner and non-static, has a
  4. reference to the outer this (an Activity for instance.) If the Message
  5. lives in the queue for a long time, which happens fairly easily when
  6. posting a delayed message for instance, you keep a reference to the
  7. Activity and "leak" all the views and resources. It gets even worse
  8. when you obtain a Message and don't post it right away but keep it
  9. somewhere (for instance in a static structure) for later use.

并且给出了他的建议写法:

  1. class OuterClass {
  2. class InnerClass {
  3. private final WeakReference<OuterClass> mTarget;
  4. InnerClass(OuterClass target) {
  5. mTarget = new WeakReference<OuterClass>(target);
  6. }
  7. void doSomething() {
  8. OuterClass target = mTarget.get();
  9. if (target != null) {
  10. target.do();
  11. }
  12. }
  13. }