欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Handler 静态内部类弱引用防止内存泄漏

程序员文章站 2022-04-19 17:36:49
...

https://blog.csdn.net/l707941510/article/details/80641444

写了一个简答的倒计时 记录一下防止遗忘

public class WelcomeActivity extends BaseActivity {

    private MyHandler myHandler;

    /*
     * 引导页
     * */
    @Override
    protected int getContentViewId() {
        return R.layout.activity_welcome;
    }

    private int time = 2;

    @Override
    protected void initUI() {
        myHandler = new MyHandler(this);
        myHandler.post(runnable);

    }


    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            time--;
            if (time > 0) {
                myHandler.postDelayed(runnable, 2000);
            } else {
                startActivity(MainActivity.class);
            }
        }
    };

    @Override
    protected void initData() {

    }

    /**
     * 声明一个静态的Handler内部类,并持有外部类的弱引用
     */
    private static class MyHandler extends Handler {

        private final WeakReference<WelcomeActivity> mActivty;

        private MyHandler(WelcomeActivity mActivty) {

            this.mActivty = new WeakReference<WelcomeActivity>(mActivty);

        }

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

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //删除所有的消息
        myHandler.removeCallbacksAndMessages(null);
    }
}