简体   繁体   中英

What's message queue in Android?

Can someone explain what's the message queue in Android? Is it the list of processes running? I can't find a good source explaining it.

I am asking because I was reading about the method post of the class View.

POST

added in API level 1 boolean post (Runnable action)

Causes the Runnable to be added to the message queue . The runnable will be run on the user interface thread.

Thank you in advance.

In simple terms a MessageQueue is a list of tasks (Messages, runnables) that will be executed in a certain thread. The Android system has a very known main thread (the UI one). The method you just saw simply adds a runnable to the list of processes that will be executed in the UI thread. Alongside with Looper and Handler, MessageQueues are part of the bulding blocks of threading in Android and they are used virtually everywhere in the system.

When would you use this method?

Whenever you want to update some UI element (View element) from another thread. Maybe you're doing some heavy lifting in another thread and want to update the UI element, you can't update the UI elements in others threads but the UI thread so you post changes to be executed in the UI thread.

You can learn more about MessageQueues here and here .

to Understand MessageQueue, you need understand executing model of android app;

Just like Javascript, Cocoa in iOS, to avoid cocurrency access racing, many App related framework adapts a single thread model.

that means there is a main thread, you put your work that need be done into the queue(MessageQueue) dedicated to this thread, there is a worker(Looper) that will reteive your work from the queue, run them one by one;

this model avoid cocurrency collision in the app;

when you need do a longtime job , you should put the work into the main thread queue, when it's to do your work in the message , you create a new thread to do this longtime job, after job is done , you put a new message into the main thread message queue from your new thread;

this picture will help you understand the running model在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM