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; }
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。