直播系统代码,Android实现倒计时的几种方案

直播系统代码,Android实现倒计时的几种方案

一、CountDownTimer的实现

 

  //倒计时的方式一
    fun countDownTimer() {
        var num = 60
        timer = object : CountDownTimer((num + 1) * 1000L, 1000L) {
            override fun onTick(millisUntilFinished: Long) {
                YYLogUtils.w("当时计数:" + num)
                if (num == 0) {
                    YYLogUtils.w("重新开始")
                    num = 60
                } else {
                    num--
                }
            }
            override fun onFinish() {
                YYLogUtils.w("倒计时结束了..." + num)
            }
        }
        timer?.start()
    }
private var timer: CountDownTimer? = null
override fun onDestroy() {
    super.onDestroy()
    timer?.cancel()
}

没什么花活,就是android.os包下面的 CountDownTimer 类的使用。内部实现使用了 Handler 进行封装。

 

二、直接用Handler的实现

 

    private var handlerNum = 60
    private val mHandler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                1 -> {
                    if (handlerNum > 0) {
                        handlerNum--
                        YYLogUtils.w("当时计数:" + handlerNum)
                        countDownHander()
                    } else {
                        stopCountDownHander()
                    }
                }
            }
        }
    }
    override fun onDestroy() {
        super.onDestroy()
        stopCountDownHander()
    
    }
    fun countDownHander() {
        mHandler.sendEmptyMessageDelayed(1, 1000)
    }
    fun stopCountDownHander() {
        mHandler.removeCallbacksAndMessages(null)
    }

 

我们可以直接使用Handler的延时发送消息实现倒计时。

当然另一种做法是使用 Runnable 来实现。

 


Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
recLen++;
txtView.setText("" + recLen);
handler.postDelayed(this, 1000);
}
public void test(){
    handler.postDelayed(runnable, 1000);
}

 

三、直接用Time、TimeTask的实现

以上是Android的倒计时方案,其实Java的Api也是支持倒计时实现的,比如 Timer 配合 TimerTask 就可以实现简单的倒计时。

 


   fun countDownTimer2() {
            var num = 60
            val timer = Timer()
            val timeTask = object : TimerTask() {
                override fun run() {
                    num--
                    YYLogUtils.w("当时计数:" + num)
                    if (num < 0) {
                        timer.cancel()
                    }
                }
            }
            timer.schedule(timeTask, 1000, 1000)
    }

 

以上就是直播系统代码,Android实现倒计时的几种方案, 更多内容欢迎关注之后的文章

 

posted @ 2023-02-03 14:08  云豹科技-苏凌霄  阅读(87)  评论(0)    收藏  举报