Inquiry Service (a) --- asynchronous message processing flow

Android service is the solution to implement the program running in the background.

Before learning services, we need to understand that the service does not automatically open thread, all the code is run by default in the main thread which, we need to open a sub-thread to perform the services which the specific service.

Android multi-threaded programming

Similar to java multithreading, commonly used way of an anonymous class.
new Thread(new Runnable(){
@Override
public void run(){
//执行具体的逻辑
}
}).start();

UI elements must be updated in the main thread

Android UI thread is not allowed in the sub-operation, but sometimes we have to perform some time-consuming operations in the sub-thread, then UI operation based on the results. To this end, ## Android provides a set of asynchronous message processing mechanism.

Asynchronous message processing mechanism

Android asynchronous message processing mechanism mainly Message, Handler, ManageQueue, Looper four parts.

Message for transferring data between different threads.
Handler is mainly used to transmit and process messages, using sendMessage () method for transmitting data, the data is ultimately processed the handleMessage () method.
MessageQueue message queue, the main storage of all messages sent by Handler.
Looper each thread MessageQueue housekeeper

Asynchronous message processing flow

1, first create a Handler object, overwriting handleMessage () method.
2, when we need to operate in the sub-UI thread, create a Message object, sent by sendMessage () method.
3, the message sent is stored in the MessageQueue, waiting Looper extracted data.
4, the data is distributed to handleMessage inside Handler () method.

Handler is created in the main thread, handleMessage () method will be executed in the main thread, the UI operation is possible. Message through an asynchronous message processing flow proceeds from sub-thread to the main thread.

发布了37 篇原创文章 · 获赞 10 · 访问量 1万+

Guess you like

Origin blog.csdn.net/OneLinee/article/details/78568984
Recommended