網站首頁 編程語言 正文
Android 倒計時一般實現方式:
- handler+postDelayed() 方式
- Timer + TimerTask + handler 方式
- ScheduledExecutorService + handler 方式
- RxJava 方式
- CountDownTimer 方式
現在因為有了協程和Flow,我們可以借助Flow這個工具,更加優雅地實現這個需求功能.
1.依賴導入
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"
2. 代碼實現
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)
}
2.1使用:
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 實現倒計時的幾種方式
使用 Timer方式:
? /**
? ? ?* 開始
? ? ?*/
? ? 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;
? ? ? ? }
? ? }
使用rxjava方式:
?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方式:
//倒計時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;
?}
原文鏈接:https://juejin.cn/post/7011018975333056519
相關推薦
- 2023-01-12 keepalived?+?nginx?實現高可用方案_nginx
- 2022-10-18 NumPy對數組按索引查詢實戰方法總結_python
- 2022-07-16 ssh遠程連接docker
- 2022-10-07 Flutter?GetPageRoute實現嵌套導航學習_IOS
- 2022-07-10 fastmock使用-只能模擬get請求
- 2022-03-24 Android?TextView文本控件介紹_Android
- 2022-06-12 python數據處理詳情_python
- 2022-08-25 C++示例講解string容器_C 語言
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支