For the use of the handler (to prevent memory leaks)

Today saw an article talking about the problem of memory leaks, which refers to the handler, speaking of clarity, put the copy down the code, posted here later when used directly used. .

public class LeakAty extends Activity {    
    private TextView tvResult;    private MyHandler handler;    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.aty_leak);
            tvResult = (TextView) findViewById(R.id.tvResult);
            handler = new MyHandler(this);
            fetchData();
    }    
    //第一步,将Handler改成静态内部类。
    private static class MyHandler extends Handler {        
        //第二步,将需要引用Activity的地方,改成弱引用。
        private WeakReference<LeakAty> atyInstance; 

        public MyHandler(LeakAty aty) {            
            this.atyInstance = new WeakReference<LeakAty>(aty);
        }
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            LeakAty aty = atyInstance == null ? null : atyInstance.get();            
            //如果Activity被释放回收了,则不处理这些消息
            if (aty == null||aty.isFinishing()) {
                return;
            }
            aty.tvResult.setText("fetch data success");
        }
    }
    private void fetchData() {        // 获取数据
        handler.sendEmptyMessage(0);
    }
    @Override
    protected void onDestroy() {        //第三步,在Activity退出的时候移除回调
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }
}
Published 17 original articles · won praise 12 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_24295537/article/details/50904262