Threads

The obvious first step is to move the infinite loop outside of the UI thread. Since Android Things is based on Android, we have some classes that we can use to improve this, so let's use a Thread to do it. The updated code looks like this:

class BlinkThreadActivity : Activity() {

private lateinit var led: Gpio

private val thread = Thread {
while(true) {
loop()
}
}

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setup()
thread.start()
}

private fun setup() {
led = RainbowHat.openLedGreen()
}

private fun loop() {
led.value = !led.value
Thread.sleep(1000)
}

override fun onDestroy() {
super.onDestroy()
thread.interrupt()
led.close()
}
}

The overall concept is very similar; we still have a setup method that is executed at the beginning and a loop method that gets executed endlessly, but now inside onCreate we just create a thread that has the infinite loop and start it. This time we can interrupt the thread as part of onDestroySo, as a first improvement, the UI thread is not blocked.

The other improvement is that onCreate does finish, so we do not tamper with the activity lifecycle.

Note that there is no need to modify the LED value on the UI thread. This is not UI in the Android sense, it is a communication done via a protocol to a wire; it is a different paradigm. It acts as a user interface, but since it is not composed of views, it is not rendered and does not require the UI Thread.

Interactions with peripherals do not need to be done on the UI thread.

One of the most powerful features of Kotlin is the integration with lambdas, and we can see it here in the definition of the thread. It gets rid of all the boilerplate code and it is a lot easier to read than the Java equivalent. 

Threads require a significant amount of resources, and while our development boards are quite powerful, it is good to use simpler solutions. Another very interesting feature of Kotlin is coroutines, which we will be exploring next.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.6.77