Android开发程序员Android技术知识

app性能优化 - 避免内存泄漏2

2017-12-14  本文已影响35人  gaom明

提出问题:

Handler造成的内存泄漏问题
Handler之所以造成内存泄漏是因为在activity销毁的时候,Handler中有未执行完的任务

解决方案:

代码参考:


    private Handler handler;

    private static class MyHandler extends Handler {
        WeakReference<SplashActivity> mWeakReferenceActivity;

        MyHandler(SplashActivity activity) {
            mWeakReferenceActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (null != mWeakReferenceActivity) {
                SplashActivity _activity = mWeakReferenceActivity.get();
                switch (msg.what) {
                    case GO_:

                        break;
                }
            }
        }
    } 

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ......
        handler = new MyHandler(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null); 
    }

上一篇 下一篇

猜你喜欢

热点阅读