› › 文章

Handler内存泄漏之使用静态内部类并持有外部类的弱引用

静态内部类或者匿名类持有外部类的引用,如果外部类正在销毁,内部类比如Handler还在延迟处理一些消息,那么其持有的外部类引用就无法销毁

解决方法:使用静态内部类并持有外部类的弱引用

package com.la.allwater;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import java.lang.ref.WeakReference;


public class HandlerMainActivity extends AppCompatActivity {

    private static final String TAG = "HandlerMainActivity";
    private Context context = null;
    private MyHandler myHandler = null;

    //Message what
    private static final int MSG_NOTIFY_UPDATE_DATA = 0x1000;
    private static final int MSG_TIME_1s = 1000;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate: ");
        context = HandlerMainActivity.this;
        setContentView(R.layout.activity_main);
        initData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //清除所有的还在消息队列中的Callback和Message
        if (null != myHandler) {
            myHandler.removeCallbacksAndMessages(null);
        }
        Log.d(TAG, "onDestroy: ");
    }

    private void initData() {
        myHandler = new MyHandler(this);
        myHandler.sendEmptyMessageAtTime(MSG_NOTIFY_UPDATE_DATA, MSG_TIME_1s);
        return;
    }

    /**
     * 非静态内部类或者匿名类持有外部类的引用,如果外部类正在销毁,
     * 内部类比如Handler还在延迟处理一些消息,那么其持有的外部类引用就无法销毁
     * <p>
     * 解决方法:使用静态内部类并持有外部类的弱引用
     */
    private static class MyHandler extends Handler {
        //使用弱引用
        private final WeakReference<Activity> weakReferenceActivity;

        public MyHandler(Activity activity) {
            weakReferenceActivity = new WeakReference<Activity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if (null == weakReferenceActivity) {
                return;
            }
            
            switch (msg.what) {
                case MSG_NOTIFY_UPDATE_DATA:
                    Log.d(TAG, "handleMessage MSG_NOTIFY_UPDATE_DATA: ");
                    break;
            }
        }
    }
}
发表评论