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

handler循环刷新UI

程序员文章站 2022-07-14 18:25:36
...

1.新建handler及runnable对象:

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if(msg.what == MSG_UPDATE) {
                //todo
            }
            super.handleMessage(msg);
        }
    };

    private Runnable task = new Runnable() {
        @Override
        public void run() {
            mHandler.sendEmptyMessage(MSG_UPDATE);
            mHandler.postDelayed(this, DELAY);
        }
    };

2.启动任务及停止任务:

    @Override
    protected void onResume() {
        super.onResume();
        mHandler.postDelayed(task, DELAY);
    }

    @Override
    protected void onPause() {
        super.onPause();
        mHandler.removeCallbacks(task);
    }