Communicating with the Main Thread

Your dedicated thread will download photos, but how will it work with the RecyclerView’s adapter to display them when it cannot directly access the main thread?

Think back to the shoe store with two Flashes. Background Flash has wrapped up his phone call to the distributor. He needs to tell Main Flash that the shoes are back in stock. If Main Flash is busy, Background Flash cannot do this right away. He would have to wait by the register to catch Main Flash at a spare moment. This would work, but it would not be very efficient.

The better solution is to give each Flash an inbox. Background Flash writes a message about the shoes being in stock and puts it on top of Main Flash’s inbox. Main Flash does the same thing when he wants to tell Background Flash that the stock of shoes has run out.

The inbox idea turns out to be really handy. The Flash may have something that needs to be done soon, but not right at the moment. In that case, he can put a message in his own inbox and then handle it when he has time.

In Android, the inbox that threads use is called a message queue. A thread that works by using a message queue is called a message loop; it loops again and again looking for new messages on its queue (Figure 26.3).

Figure 26.3  Flash dance

Figure shows Flash Dance.

A message loop consists of a thread and a looper. The Looper is the object that manages a thread’s message queue.

The main thread is a message loop and has a looper. Everything your main thread does is performed by its looper, which grabs messages off of its message queue and performs the task they specify.

You are going to create a background thread that is also a message loop. You will use a class called HandlerThread that prepares a Looper for you.

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

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