This Handler class should be static or leaks ….
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嵌套类,并且使用对外部类的弱应用。
使用范例:
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 45 46 |
package cn.beyondcompare.statichandlerdemo; import java.lang.ref.WeakReference; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.app.Activity; public class MainActivity extends Activity { MyHandler handler = new MyHandler(this); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); test(); } static class MyHandler extends Handler { WeakReference<mainactivity> mActivity; MyHandler(MainActivity activity) { mActivity = new WeakReference</mainactivity><mainactivity>(activity); } @Override public void handleMessage(Message msg) { MainActivity theActivity = (MainActivity) mActivity.get(); switch (msg.what) { case 0: theActivity.test1(); break; } } }; private void test() { handler.sendEmptyMessage(0); } private void test1() { } } |