Kotlin에서는 Timer를 쉽게 구성하기 위한 스레드를 제공합니다. 바로 kotlin.concurrent.timer 인데요. initialDelay, period 값을 지정하여 타이머의 동작을 핸들링 할 수 있다는 특징을 가지고 있습니다. 아래의 코드는 예시 코드입니다.
import kotlin.concurrent.timer
class MainActivity : AppCompatActivity() {
private var countDownSecond = 10
private var currentDeciSecond = 0
private var timer:Timer? = null
override fun onCreate(savedInstanceState: Bundle?) {
...
start()
}
private fun start() {
timer = timer(initialDelay = 0, period = 100) {
currentDeciSecond += 1
val minute = currentDeciSecond.div(10) / 60
val second = currentDeciSecond.div(10) % 60
val tick = currentDeciSecond % 10
val timeText = String.format("%02d:%02d", minute, second)
}
}
}
위 코드에서 timer의 파라메터로 period를 100ms 즉 0.1초로 설정하여 0.1초마다 텍스트가 업데이트 되도록 구성하였습니다. 여기서 주의할 점은 해당 텍스트를 UI에 업데이트 할때는 runOnUiThread 를 활용하여 Runnuable 객체를 넘겨주어 처리해야 합니다.
그 이유는 Kotlin의 Timer같은 경우는 Main Thread가 아닌 다른 Worker Thread이기 때문에 해당 스레드에서 UI에 접근하게 되면 Exeception이 발생하게 됩니다. 추후에 Thread에 대한 추가적인 포스팅을 진행하겠습니다. 감사합니다.
'Android > Skill' 카테고리의 다른 글
Android Foreground Service 미디어 플레이어 Style 적용하기 (0) | 2023.01.18 |
---|---|
Android Kotlin Toolbar 메뉴 생성하기 (0) | 2023.01.16 |
Android(kotlin) Room DB 사용법 (0) | 2023.01.02 |
안드로이드 Constraint Flow를 활용하여 TableLayout 구성하기 (0) | 2023.01.02 |
(Kotlin) String 값이 숫자인지, 숫자 판별 로직 (0) | 2023.01.01 |
댓글