Handler Class Should be Static or Leaks Occur

在使用Handler更新UI的時候,我是這樣寫的:html

public class SampleActivity extends Activity {

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

看起來很正常的,可是 Android Lint 卻給出了警告:java

This Handler class should be static or leaks might occurandroid

意思是說:這個Handler 必須是static的,不然就會引起內存泄露。app

其實,對於這個問題,Android Framework 的工程師 Romain Guy 早已經在Google論壇上作出過解釋,而且給出了他的建議寫法: ide

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.  
oop

他的建議寫法是:post

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();     
           }
     }
}

下面,咱們進一步解釋一下:

1.Android App啓動的時候,Android Framework 爲主線程建立一個Looper對象,這個Looper對象將貫穿這個App的整個生命週期,它實現了一個消息隊列(Message  Queue),而且開啓一個循環來處理Message對象。而Framework的主要事件都包含着內部Message對象,當這些事件被觸發的時候,Message對象會被加到消息隊列中執行。
2.當一個Handler被實例化時(如上面那樣),它將和主線程Looper對象的消息隊列相關聯,被推到消息隊列中的Message對象將持有一個Handler的引用以便於當Looper處理到這個Message的時候,Framework執行Handler的handleMessage(Message)方法。
3.在 Java 語言中,非靜態匿名內部類將持有一個對外部類的隱式引用,而靜態內部類則不會。 this

到底內存泄露是在哪裏發生的呢?如下面代碼爲例:google

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的上下文了,以下所示:spa

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


參考:

[1]https://groups.google.com/forum/?fromgroups=#!msg/android-developers/1aPZXZG6kWk/lIYDavGYn5UJ
[2]http://www.androiddesignpatterns.com/2013/01/inner-class-handler-memory-leak.html
[3]http://stackoverflow.com/questions/11407943/this-handler-class-should-be-static-or-leaks-might-occur-incominghandler 

相關文章
相關標籤/搜索