Handler内存泄漏避免方法

内存泄漏概念 对象在内存heap堆中中分配的空间, 当不再使用或没有引用指向的情况下, 仍不能被GC正常回收的情况。 多数出现在不合理的编码情况下, 比如在Activity中注册了一个广播接收器, 但是在页面关闭的时候进行unRegister, 就会出现内存溢出的现象。 通常情况下, 大量的内存泄漏会造成OOM。

当使用AndroidStudio进行handler的编写时,会出现这样的黄色警告,警告的具体内容为:Since this Handler is declared as an inner class, it may prevent the outer class from being garbage collected. If the Handler is using a Looper or MessageQueue for a thread other than the main thread, then there is no issue. If the Handler is using the Looper or MessageQueue of the main thread, you need to fix your Handler declaration, as follows: Declare the Handler as a static class; In the outer class, instantiate a WeakReference to the outer class and pass this object to your Handler when you instantiate the Handler; Make all references to members of the outer class using the WeakReference object.

这段话的大体意思为:

一旦Handler被声明为内部类,那么可能导致它的外部类不能够被垃圾回收。如果Handler是在其他线程(我们通常成为worker thread)使用Looper或MessageQueue(消息队列),而不是main线程(UI线程),那么就没有这个问题。如果Handler使用Looper或MessageQueue在主线程(main thread),你需要对Handler的声明做如下修改:

声明Handler为static类;在外部类中实例化一个外部类的WeakReference(弱引用)并且在Handler初始化时传入这个对象给你的Handler;将所有引用的外部类成员使用WeakReference对象。


当出现上面这样的情况时要怎么去除呢?

解决方法一:

编写一个静态的内部类,然后让这个内部类继承Handler,之后再在这个内部类里面使用弱引用的方法。具体代码如下:

private static class CopyHandler extends Handler {
    WeakReference<MainActivity> mactivity;

    CopyHandler(MainActivity activity) {
        this.mactivity = new WeakReference<MainActivity>(activity);
    }

    @Override
    public void handleMessage(Message msg) {
        final MainActivity activity = mactivity.get();
        if (msg.what == 1) {
            textView.setText("" + msg.obj);
        } else {
            textView.setText("buhaole");
        }
    }
}

解决方法二:

假如我们是在一个不断执行的线程内部使用handler,此时Activity关闭,线程却仍在执行,这种情况下就应该

在onDestroy()中使用handler.removeCallbacksAndMessages(null)。这种情况是比如你从启动界面调到主界面的时候会用到

handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        StartMainactivity();
    }
}, 3000);
延迟个3秒钟,这时候你就要记得在onDestroy方法中把所有的消息和回调移除。
 
 


猜你喜欢

转载自blog.csdn.net/qq_38363506/article/details/80054641