Android Handler leak 分析及解决办法

静态内部类只能访问外部类的静态成员,因为非静态成员必须依附于某个具体的对象,而静态内部类不需要要

静态内部类可以直接实例化,不需要绑定到外部类上再去实例化

handler出现泄漏的两个原因:

1)message没有清楚干净

2)handler持有的主线程的COntext实例

解决方案:

 

1) message:在Context的destroy的时候利用handler.removeCallbacksAndMessages(null)来清除

2)静态内部类+WeakReference

public class MyActivity extends Activity {
    private MyHandler mHandler;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 
        mHandler = new MyHandler(this);
    }
 
    @Override
    protected void onDestroy() {
        // Remove all Runnable and Message.
       mHandler.removeCallbacksAndMessages(null);
 
        super.onDestroy();
    }
 
    static class MyHandler extends Handler {
     private WeakReference<MyActivity> mOuter;

        public MyHandler(MyActivity activity) {
            mOuter = new WeakReference<MyActivity>(activity);
        }
 
        @Override
        public void handleMessage(Message msg) {
            MyActivity outer = mOuter.get();
            if (outer != null) {
                // Do something with outer as your wish.
            }
        }
    }
}

 

posted @ 2015-10-27 14:05  我在途中  阅读(449)  评论(0编辑  收藏  举报