Android中Handler导致的内存泄露

http://www.androiddesignpatterns.com/2013/01/inner-class-handler-memory-leak.html

Consider the following code:

1
2
3
4
5
6
7
8
9

public class SampleActivity extends Activity {

  private final Handler mLeakyHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
      // ...
    }
  }
}

While not readily obvious, this code can cause cause a massive memory leak. Android Lint will give the following warning:

In Android, Handler classes should be static or leaks might occur.

But where exactly is the leak and how might it happen? Let‘s determine the source of the problem by first documenting what we know:

  1. When an Android application first starts, the framework creates a Looper object for the application‘s main thread. ALooper implements a simple message queue, processing Message objects in a loop one after another. All major application framework events (such as Activity lifecycle method calls, button clicks, etc.) are contained insideMessage objects, which are added to the Looper‘s message queue and are processed one-by-one. The main thread‘sLooper exists throughout the application‘s lifecycle.
  2. When a Handler is instantiated on the main thread, it is associated with the Looper‘s message queue. Messages posted to the message queue will hold a reference to the Handler so that the framework can callHandler#handleMessage(Message) when the Looper eventually processes the message.
  3. In Java, non-static inner and anonymous classes hold an implicit reference to their outer class. Static inner classes, on the other hand, do not.

So where exactly is the memory leak? It‘s very subtle, but consider the following code as an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

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() { /* ... */ }
    }, 1000 * 60 * 10);

    // Go back to the previous Activity.
    finish();
  }
}

When the activity is finished, the delayed message will continue to live in the main thread‘s message queue for 10 minutes before it is processed. The message holds a reference to the activity‘s Handler, and the Handler holds an implicit reference to its outer class (the SampleActivity, in this case). This reference will persist until the message is processed, thus preventing the activity context from being garbage collected and leaking all of the application‘s resources. Note that the same is true with the anonymous Runnable class on line 15. Non-static instances of anonymous classes hold an implicit reference to their outer class, so the context will be leaked.

To fix the problem, subclass the Handler in a new file or use a static inner class instead. Static inner classes do not hold an implicit reference to their outer class, so the activity will not be leaked. If you need to invoke the outer activity‘s methods from within the Handler, have the Handler hold a WeakReference to the activity so you don‘t accidentally leak a context. To fix the memory leak that occurs when we instantiate the anonymous Runnable class, we make the variable a static field of the class (since static instances of anonymous classes do not hold an implicit reference to their outer class):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

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, 1000 * 60 * 10);

    // Go back to the previous Activity.
    finish();
  }
}

The difference between static and non-static inner classes is subtle, but is something every Android developer should understand. What‘s the bottom line? Avoid using non-static inner classes in an activity if instances of the inner class could outlive the activity‘s lifecycle. Instead, prefer static inner classes and hold a weak reference to the activity inside.

时间: 2024-10-29 19:11:56

Android中Handler导致的内存泄露的相关文章

Android中Handler引起的内存泄露

在Android常用编程中,Handler在进行异步操作并处理返回结果时经常被使用.通常我们的代码会这样实现. 但是,其实上面的代码可能导致内存泄露,当你使用Android lint工具的话,会得到这样的警告 In Android, Handler classes should be static or leaks might occur, Messages enqueued on the application thread’s MessageQueue also retain their t

Android 中 Handler 引起的内存泄露

在Android常用编程中,Handler在进行异步操作并处理返回结果时经常被使用.其实这可能导致内存泄露,代码中哪里可能导致内存泄露,又是如何导致内存泄露的呢?那我们就慢慢分析一下.http://www.jinhusns.com/Products/Download/?type=xcj 在Android常用编程中,Handler在进行异步操作并处理返回结果时经常被使用.通常我们的代码会这样实现. public class SampleActivity extends Activity {   

Android开发——Handler引起的内存泄露

在Android异步消息处理中, Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { // } }; 但当我们这么写时,编译器会给出警告提示:Handler类应该是静态的,可能发生内存泄漏. 原因: 在Java中,非静态的内部类和匿名内部类都会隐式地持有其外部类的引用.静态的内部类不会持有外部类的引用. 这里Handler是一个匿名内部类的实例,其持有外面的Activity的引

解决android中EditText导致的内存泄漏问题

开发中用到了LeankCanary,在一个简单的页面中(例如 :仅仅 包含Edittext),也会导致内训泄漏,为此,我在网上找了大量资料,最终解决.例如一个布局:<LinearLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"android:focusable="true"android:focusableInTouchMode=&qu

UIActionSheet关闭动画过程中调用delegate = nil 导致的内存泄露

UIActionSheet在动画期间(ActionSheet button点击之后,到didDismissWithButtonIndex调用完成之前)设置delegate为空会导致delegate无法释放. 先来看个例子: 例子中创建一个UIActionSheet,并在按钮点击之后0.1秒(关闭动画结束前)设置delegate = nil. #import "LIViewController.h" @class UIActionSheetDelegateImpl; static UIA

Android OOM(Out of memory) 内存泄露基本知识

Android OOM(Out of memory) 内存泄露基本知识 转载至:http://blog.csdn.net/emilychai2010/article/details/12710135 1. 内存泄露 2. Android里的垃圾回收 3. Heap 4. 调试 5. 常见的内存泄露 1.什么是内存泄露(memory leak)? A "memory leak" in your code is when you keep a reference to an object

深入解析Android中Handler消息机制

Android提供了Handler 和 Looper 来满足线程间的通信.Handler先进先出原则.Looper类用来管理特定线程内对象之间的消息交换(MessageExchange).Handler消息机制可以说是Android系统中最重要部分之一,所以,本篇博客我们就来深入解析Android中Handler消息机制. Handler的简单使用 为什么系统不允许子线程更新UI 因为的UI控件不是线程安全的. 如果在多线程中并发访问可能会导致UI控件处于不可预期的状态,那为什么不对UI控件的访

Android中Handler 、Thread和Runnable之间的关系

在多线程编程的时候,我们经常会用到Handler,Thread和Runnable这三个类,我们来看看这三个类之间是怎么样的关系? 首先说明Android的CPU分配的最小单元是线程,Handler一般是在某个线程里创建的,因而Handler和Thread就是相互绑定的,一一对应. 而Runnable是一个接口,Thread是Runnable的子类.可以说,他俩都算一个进程. HandlerThread顾名思义就是可以处理消息循环的线程,他是一个拥有Looper的线程,可以处理消息循环. 与其说H

在java中如何创建一个内存泄露

今天访问java 并发编程网,看到一个翻译征集令,并发编程网的作者从stackoverflow 网站上选取了一些经典问答,遂决定翻译几篇 征集令地址:http://ifeve.com/stackoverflow-assembly/ 翻译系列文章: 1.Java 核心类库中的一些设计模式 2. hashMap 与hashTable之间的区别 3.  在java中如何创建一个内存泄露 译文: 在java中如何创建一个内存泄露 问题: 我之前参加了一个面试, 被问到在java中如何创建一个内存泄露.不