Instance of custom looper with message loop for Android thread

Instance of custom looper with message loop for Android thread

The UI thread of Android system is a thread with looper mechanism. Meanwhile, Android also provides a handler thread class encapsulated with looper. This thread can bind the handler () object, send messages to the thread through the handler's sendmessage() function, and process the messages received by the thread through the handlemessage() function. So it's more abstract, so this paper uses the basic @ R_ 404_ 1713 @ library to implement a thread with a looper to help beginners understand how such a looper works.

1. First, we complete a simple threading framework.

As shown in the above code, mlooperrunnable. Run() loop executes the thread task, and mislooperquit is the condition for the thread to exit the loop. Next, we will add the sending and processing code of the message.

2. Add the message sending and processing code of thread loop

(1) Define message structure and create message queue

(2) Create mutexes and conditional variables

(3) Create a function to send a message

(4) Create a function to process messages

(5) Parse the message in the mlooperrunnable. Run() loop

(6) Modify the stop() function of the thread to wake up the dormant message loop

Here, a basic thread class encapsulation with message loop is completed. I believe you should understand how the system implements message loop from the process of writing this code.

If you have any questions, please leave a message or go to the community of this site for exchange and discussion. Thank you for reading. I hope it can help you. Thank you for your support to this site!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>