Kotlin使用flow實(shí)現(xiàn)倒計(jì)時(shí)功能(示例詳解)
一、效果圖
二、ExtendContext.kt 文件代碼
注意:創(chuàng)建ExtendContext.kt選擇file
使用kotlin擴(kuò)展方法的特性創(chuàng)建countDown擴(kuò)展方法,避免多個(gè)地方使用倒計(jì)時(shí)重復(fù)創(chuàng)建countDown方法
package com.example.baselib.extension import androidx.fragment.app.FragmentActivity import androidx.lifecycle.lifecycleScope import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.onCompletion import kotlinx.coroutines.flow.onStart import kotlinx.coroutines.launch fun FragmentActivity.countDown( timeMillis: Long = 1000,//默認(rèn)時(shí)間間隔 1 秒 time: Int = 3,//默認(rèn)時(shí)間為 3 秒 start: (scop: CoroutineScope) -> Unit, end: () -> Unit, next: (time: Int) -> Unit, error: (msg: String?) -> Unit ) { lifecycleScope.launch { flow { (time downTo 1).forEach { delay(timeMillis) emit(it) } }.onStart { start(this@launch) }.onCompletion { end() }.catch { error(it.message ?: "countDown 出現(xiàn)未知錯(cuò)誤") }.collect { next(it) } } }
三、MainActivity.kt代碼
package com.example.testkotlin import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import com.example.baselib.extension.countDown import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.cancel class MainActivity : AppCompatActivity() { private var mCountDown: CoroutineScope? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) loadData() } private fun loadData() { this.countDown(time = 5, start = { mCountDown = it }, end = { Log.i("==", "倒計(jì)時(shí)結(jié)束了") }, next = { Log.i("==", "剩余 $it 秒") }, error = { }) } override fun onDestroy() { mCountDown?.let { it.cancel() } super.onDestroy() } }
四、build.gradle.kts代碼
plugins { id("com.android.application") id("org.jetbrains.kotlin.android") } android { namespace = "com.example.testkotlin" compileSdk = 34 defaultConfig { applicationId = "com.example.testkotlin" minSdk = 23 targetSdk = 34 versionCode = 1 versionName = "1.0" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { isMinifyEnabled = false proguardFiles( getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro" ) } } compileOptions { sourceCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = "1.8" } } dependencies { implementation("androidx.core:core-ktx:1.9.0") implementation("androidx.appcompat:appcompat:1.6.1") implementation("com.google.android.material:material:1.11.0") implementation("androidx.constraintlayout:constraintlayout:2.1.4") testImplementation("junit:junit:4.13.2") androidTestImplementation("androidx.test.ext:junit:1.1.5") androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1") }
擴(kuò)展:
kotlin——倒計(jì)時(shí)(CountDownTimer和flow形式)
一、kotlin倒計(jì)時(shí)-谷歌CountDownTimer
簡介:谷歌官方推薦使用CountDownTimer,非常的簡單好用,代碼也很少
代碼
var TotalTime : Long = 2*60*60*1000 //總時(shí)長 2小時(shí) var countDownTimer=object : CountDownTimer(TotalTime,1000){//1000ms運(yùn)行一次onTick里面的方法 override fun onFinish() { Log.d(TAG,"==倒計(jì)時(shí)結(jié)束") } override fun onTick(millisUntilFinished: Long) { var hour=millisUntilFinished/1000/60/60 var minute=millisUntilFinished/1000/60%60 var second=millisUntilFinished/1000%60 Log.d(TAG,"==倒計(jì)時(shí)"+hour+"小時(shí)"+minute+"分"+second+"秒") } }.start()
使用說明
1、把這段代碼放到類的屬性里就可以自動運(yùn)行了
2、把上面代碼中的.start()去掉,然后在需要用到的地方countDownTimer.start()就可以運(yùn)行了
二、kotlin倒計(jì)時(shí)-谷歌CountDownTimer
引入?yún)f(xié)程:implementation ‘androidx.lifecycle:lifecycle-runtime-ktx:2.2.0’ // 協(xié)程lifecycleScope
倒計(jì)時(shí)代碼(擴(kuò)展方法):
import android.util.Log import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.lifecycleScope import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.* import kotlinx.coroutines.flow.onCompletion import kotlinx.coroutines.flow.onStart import kotlinx.coroutines.launch /** * 擴(kuò)展方法 * 倒計(jì)時(shí)的實(shí)現(xiàn) */ fun AppCompatActivity.countDown( time: Int = 30, start: (scop: CoroutineScope) -> Unit, next: (time: String) -> Unit, end: () -> Unit ) { lifecycleScope.launch { // 在這個(gè)范圍內(nèi)啟動的協(xié)程會在Lifecycle被銷毀的時(shí)候自動取消 flow { (time downTo 0).forEach { delay(1000) emit(it) } }.onStart { // 倒計(jì)時(shí)開始 ,在這里可以讓Button 禁止點(diǎn)擊狀態(tài) start(this@launch) }.onCompletion { // 倒計(jì)時(shí)結(jié)束 ,在這里可以讓Button 恢復(fù)點(diǎn)擊狀態(tài) end() }.catch { //錯(cuò)誤 Log.e("", it.message ?: "Unkown Error") }.collect { // 在這里 更新值來顯示到UI next(it.toString()) } } }
到此這篇關(guān)于Kotlin使用flow實(shí)現(xiàn)倒計(jì)時(shí)功能的文章就介紹到這了,更多相關(guān)Kotlin倒計(jì)時(shí)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Android進(jìn)階從字節(jié)碼插樁技術(shù)了解美團(tuán)熱修復(fù)實(shí)例詳解
這篇文章主要為大家介紹了Android進(jìn)階從字節(jié)碼插樁技術(shù)了解美團(tuán)熱修復(fù)實(shí)例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01android 實(shí)現(xiàn)控件左右或上下抖動教程
這篇文章主要介紹了android 實(shí)現(xiàn)控件左右或上下抖動教程,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03Android中ViewPager實(shí)現(xiàn)滑動條及與Fragment結(jié)合的實(shí)例教程
ViewPager類主要被用來實(shí)現(xiàn)可滑動的視圖功能,這里我們就來共同學(xué)習(xí)Android中ViewPager實(shí)現(xiàn)滑動條及與Fragment結(jié)合的實(shí)例教程,需要的朋友可以參考下2016-06-06Android廣播接實(shí)現(xiàn)監(jiān)聽電話狀態(tài)(電話的狀態(tài),攔截)
這篇文章主要介紹了Android廣播接實(shí)現(xiàn)監(jiān)聽電話狀態(tài)(電話的狀態(tài),攔截) 的相關(guān)資料,需要的朋友可以參考下2016-03-03Android中Java instanceof關(guān)鍵字全面解析
instanceof關(guān)鍵字用于判斷一個(gè)引用類型變量所指向的對象是否是一個(gè)類(或接口、抽象類、父類)的實(shí)例.這篇文章主要介紹了Android中Java instanceof關(guān)鍵字全面解析的相關(guān)資料,需要的朋友可以參考下2016-07-07Android Studio連接SQLite數(shù)據(jù)庫的登錄注冊實(shí)現(xiàn)
這篇文章主要介紹了Android Studio連接SQLite數(shù)據(jù)庫的登錄注冊實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-06-06Android水波紋載入控件CircleWaterWaveView使用詳解
這篇文章主要為大家詳細(xì)介紹了Android水波紋載入控件CircleWaterWaveView使用方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-01-01Kotlin?this關(guān)鍵字的使用實(shí)例詳解
這篇文章主要介紹了Kotlin?this關(guān)鍵字的使用實(shí)例,在Kotlin中,this關(guān)鍵字允許我們引用一個(gè)類的實(shí)例,該類的函數(shù)恰好正在運(yùn)行。此外,還有其他方式可以使this表達(dá)式派上用場2023-02-02