- Published on
Android Thread: Practicing Code with a Clock Application
- Authors
- Name
- Dan Tech
- @dan_0xff
After the article about Thread in Android, it's time for you to write an Android program using Thread!
The focus of this application will guide you to write the simplest program to display the current time of the device. The tools used are Thread and Activity Lifecycle.
private val clockHandlerThread: HandlerThread = HandlerThread("Clock-Handler-Thread").apply {
start()
}
private val clockHandler: Handler by lazy {
Handler(clockHandlerThread.looper)
}
private val mainHandler: Handler = Handler(Looper.getMainLooper())
private val clockRunnable: Runnable = object : Runnable {
override fun run() {
mainHandler.post {
updateTime()
}
clockHandler.postDelayed(this, 1000)
}
}
private fun startClock() {
updateTime()
clockHandler.postDelayed(clockRunnable, 1000)
}
You can find the complete source code here.