Published on

Android Thread: Looper, Handler, HandlerThread, Executor (P2)

Authors

Following up on the Android Thread Part 1 article, in this article I will go into more detail about the basic concepts when working with Threads in Android.

Reviewing Knowledge: What is a Thread?

A Thread is a unit used to execute a program's code. Or you can also understand Thread as the environment for executing a piece of the program's code.

In Android, you have many options for manipulating Threads, and in this article I will introduce them one by one.

In reality, not many Android programmers nowadays directly use Threads for their processing. However, this is a knowledge area that every programmer should grasp in order to understand how programs execute and write better code.

Thread

In Android, Threads are divided into 2 main types: Main Thread and Background Thread. The Main Thread is used for handling updates and events of the user interface; on the other hand, the Background Thread is the representative of choice for heavy logic and calculations. When using Background Threads to handle heavy logic, we avoid app lag, stutter, and freezes, improving the user experience.

Note that in Android, logic for updating the interface and handling Input can only be run on the Main Thread. Therefore, we need appropriate handling to switch execution between the Main Thread and the Background Thread and vice versa, in order to optimize the program.

Take a look at the code below to see how to use Thread for processing calculations and updating the interface on the Main Thread (UI Thread).

class MainActivity : AppCompatActivity {
  private lateinit var textViewCount: TextView
  // default functions
  fun handleLargeProcess() {
   // switch logic to Background Thread for execution
    Thread {
      var count = 0
      while (count = 1 Thread) are packaged together in a data structure (usually a List or Queue) for a specific purpose.

Basically, Executor is no different from HandlerThread, but on a larger scale, a different approach. If HandlerThread is using 1 Thread to put executable code into a MessageQueue for sequential execution, then Executor provides us with a variety of solutions.

ThreadPoolExecutor can be mentioned as an Implementation of Executor, it provides us with a Pool that can contain many Threads inside it. This means that at one time ThreadPoolExecutor can execute more than 1 task simultaneously. ThreadPoolExecutor also provides a solution similar to HandlerThread, which is to cancel a scheduled task. However, there may still be some limitations: ThreadPoolExecutor does not allow us to schedule a task by time like HandlerThread (actually I don't think this is important, because it's just a design, we can add it ourselves if necessary) : )

I won't add example code. No one uses Executor in Android these days. Everyone has switched to RxJava and Kotlin Coroutines!