Android 倒计时一般实现方式: handler+postDelayed() 方式Timer + TimerTask + handler 方式ScheduledExecutorS
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;
}
到此这篇关于Android 使用flow实现倒计时的方式的文章就介绍到这了,更多相关android flow倒计时内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: Android 使用flow实现倒计时的方式
本文链接: https://lsjlt.com/news/146940.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-01-21
2023-10-28
2023-10-28
2023-10-27
2023-10-27
2023-10-27
2023-10-27
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0