Handler有可能引起内存溢出

来源:互联网 发布:base64 decode php 编辑:程序博客网 时间:2024/05/16 07:26

Handler作为Activity的内部类有可能会导致内存泄露的问题。具体如何解决,在国外有人提出,如下:

Issue: Ensures that Handler classes do not hold on to a reference to an outer class

In Android, Handler classes should be static or leaks might occur. Messages enqueued on the application thread's MessageQueue also retain their target Handler. If the Handler is an inner class, its outer class will be retained as well. To avoid leaking the outer class, declare the Handler as a static nested class with a WeakReference to its outer class. 

大体翻译如下:

Handler类应该应该为static类型,否则有可能造成泄露。在程序消息队列中排队的消息保持了对目标Handler类的应用。如果Handler是个内部类,那么它也会保持它所在的外部类的引用。为了避免泄露这个外部类,应该将Handler声明为static嵌套类,并且使用对外部类的弱应用。

使用范例:

[java] view plaincopy
  1. static class MyHandler extends Handler {  
  2.                 WeakReference<PopupActivity> mActivity;  
  3.   
  4.                 MyHandler(PopupActivity activity) {  
  5.                         mActivity = new WeakReference<PopupActivity>(activity);  
  6.                 }  
  7.   
  8.                 @Override  
  9.                 public void handleMessage(Message msg) {  
  10.                         PopupActivity theActivity = mActivity.get();  
  11.                         switch (msg.what) {  
  12.                         case 0:  
  13.                                 theActivity.popPlay.setChecked(true);  
  14.                                 break;  
  15.                         }  
  16.                 }  
  17.         };  
  18.   
  19.         MyHandler ttsHandler = new MyHandler(this);  
  20.         private Cursor mCursor;  
  21.   
  22.         private void test() {  
  23.                 ttsHandler.sendEmptyMessage(0);  
  24.         }