时间:2022-11-10 09:22:44 | 栏目:Android代码 | 点击:次
Android 倒计时一般实现方式:
现在因为有了协程和Flow,我们可以借助Flow这个工具,更加优雅地实现这个需求功能.
api 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.2' api 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.1' // lifecycleScope(可选) api "androidx.lifecycle:lifecycle-runtime-ktx:2.2.0"
fun countDownCoroutines( total: Int, scope: CoroutineScope, onTick: (Int) -> Unit, onStart: (() -> Unit)? = null, onFinish: (() -> Unit)? = null, ): Job { return flow { for (i in total downTo 0) { emit(i) delay(1000) } }.flowOn(Dispatchers.Main) .onStart { onStart?.invoke() } .onCompletion { onFinish?.invoke() } .onEach { onTick.invoke(it) } .launchIn(scope) }
private var mCountdownJob: Job? = null mBinding.btnStart.setOnClickListener { mCountdownJob = countDownCoroutines(60, lifecycleScope, onTick = { second -> mBinding.text.text = "${second}s后重发" }, onStart = { // 倒计时开始 }, onFinish = { // 倒计时结束,重置状态 mBinding.text.text = "发送验证码" }) } mBinding.btnStop.setOnClickListener { // 取消倒计时 mCountdownJob?.cancel()
其他的完整Demo https://github.com/dahui888/kotlinpractice
补充:
下面是小编收集整理Android 实现倒计时的几种方式
/** * 开始 */ public void startTimer() { if (timer == null) { timer = new Timer(); } if (timerTask == null) { timerTask = new TimerTask() { @Override public void run() { Message message = new Message(); message.what = 2; handler.sendMessage(message); } }; } if (timer != null && timerTask != null) { timer.schedule(timerTask, 0, 2000); } } /** * 暂停定时器 */ public void stopTimer() { if (timer != null) { timer.cancel(); timer = null; } if (timerTask != null) { timerTask.cancel(); timerTask = null; } }
private void countDown() { mdDisposable = Flowable.intervalRange(0, Constant.COUNT_DOWN, 0, 1,TimeUnit.SECONDS) .observeOn(AndroidSchedulers.mainThread()) .doOnNext((aLong) -> LogUtils.e("倒计时--" + aLong)) .doOnComplete(() -> randomSelectSeat()) .subscribe(); } /** * 销毁 */ @Override protected void onDestroy() { if (mdDisposable != null) { mdDisposable.dispose(); } super.onDestroy(); }
//倒计时CountDownTimer //每过1000毫秒执行一次onTick //倒计时完成执行onFinish CountDownTimer timer = new CountDownTimer(5000, 1000){ @Override public void onTick(long sin) { Toast.makeText(MainActivity.this, "" + sin/1000, Toast.LENGTH_SHORT).show(); } @Override public void onFinish() { Toast.makeText(MainActivity.this, "倒计时完成", Toast.LENGTH_SHORT).show(); } }; //开始 timer.start(); //暂停 if (timer != null) { timer.cancel(); timer = null; }