Android倒计时的开始与停止,剩余时分秒的展示

时间:2022-03-27 02:29:21

1.声明开启倒计时相关方法

Handler handler = new Handler();
    Runnable update_thread = new Runnable() {
        @Override
        public void run() {
            leftTime--;
            LogUtil.e("leftTime="+leftTime);
            if (leftTime > 0) {
                //倒计时效果展示
                String formatLongToTimeStr = formatLongToTimeStr(leftTime);
                sureBtn.setText(formatLongToTimeStr);
                //每一秒执行一次
                handler.postDelayed(this, 1000);
            } else {//倒计时结束
                //处理业务流程

                //发送消息,结束倒计时
                Message message = new Message();
                message.what = 1;
                handlerStop.sendMessage(message);
            }
        }
    };

2.声明停止倒计时的方法

final Handler handlerStop = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    leftTime = 0;
                    handler.removeCallbacks(update_thread);
                    break;
            }
            super.handleMessage(msg);
        }

    };

3.页面关闭时,销毁定时器,重写onDestory方法

@Override
    protected void onDestroy() {
        super.onDestroy();
        leftTime = 0;
        handler.removeCallbacks(update_thread);
    }

4.开启倒计时

handler.postDelayed(update_thread, 1000);

5.倒计时展示剩余时分秒的两种方法
方法一 展示剩余时、分、秒:

public String formatLongToTimeStr(Long l) {
        int hour = 0;
        int minute = 0;
        int second = 0;
        second = l.intValue() ;
        if (second > 60) {
            minute = second / 60;   //取整
            second = second % 60;   //取余
        }
        if (minute > 60) {
            hour = minute / 60;
            minute = minute % 60;
        }
        String strtime = "剩余:"+hour+"小时"+minute+"分"+second+"秒";
        return strtime;
    }

方法二 展示剩余天、时、分、秒:

public String formatLongToTimeStr(Long date) {
        long day = date / (60 * 60 * 24);
        long hour = (date / (60 * 60) - day * 24);
        long min = ((date / 60) - day * 24 * 60 - hour * 60);
        long s = (date - day*24*60*60 - hour*60*60 - min*60);
        String strtime = "剩余:"+day+"天"+hour+"小时"+min+"分"+s+"秒";
        return strtime;
    }

6.最终效果图
Android倒计时的开始与停止,剩余时分秒的展示