Java中Handler的标准使用方式

在Java语言中,直接将Handler声明为Activity的内部类去使用Handler,非静态内部类会持有外部类的一个隐试引用,这样就可能造成外部类无法被垃圾回收,(Handler应认为是属于内核的对象,内核和activity所在线程是异步的,当Activity被销毁时内核可能还在用这个Handler,于是内核不让释放Handler,于是这个Handler没用了,却错过了唯一一次被销毁 的机会,就这样占据着内存)从而导致内存泄漏。

故而,给出规范的Handler使用方式如下:

1.定义一个Handler 的import android.os.Handler;

 

import android.os.Handler;
import java.lang.ref.WeakReference;

/**
 * @author Harper
 * @date 2021/11/11
 * note:
 */
public class UiHandler<T> extends Handler {

    protected WeakReference<T> ref;

    public UiHandler(T cla) {
        ref = new WeakReference<>(cla);
    }
    
    public T getRef() {
        return ref != null ? ref.get() : null;
    }
}

 

2.Handler在Activity中使用实例:

    private final MyHandler mHandler = new MyHandler(this);

    public static void startActivity(Context context) {
        Intent intent = new Intent(context, HandleActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_handle);
        mHandler.post(RUNNABLE);
    }

    private static final Runnable RUNNABLE = () -> {

    };

    private static class MyHandler extends UiHandler<HandleActivity> {

        private MyHandler(HandleActivity activity) {
            super(activity);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            HandleActivity activity = getRef();
            if (activity != null) {
                if (activity.isFinishing()) {
                    return;
                }
                int msgId = msg.what;
                if (msgId == 1) {
                    //处理消息
                }
            }
        }
    }

    

 

posted on 2021-11-11 10:27  HarperSun  阅读(2493)  评论(0编辑  收藏  举报

导航