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

提出问题:

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

解决方案:

  • Handler声明成静态的并且弱引用Activity。
  • 在onDestory中移除未执行完的任务。

代码参考:


    private Handler handler;

    private static class MyHandler extends Handler {
        WeakReference 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); 
    }

你可能感兴趣的:(app性能优化 - 避免内存泄漏2)