For performance optimizations, Android UI operations are not thread-safe, and thread-safe issues can occur if multiple threads are working on the UI at the same time. So, Google's great gods came up with a simple and crude solution: only the main thread can manipulate the UI.
To enable the UI thread to communicate with other threads, the handler messaging mechanism is introduced.
Common methods:
Handlemessage () Methods for handling messages
Sendemptymessage () Send empty message
SendMessage () Send Message
Sendemptymessagedelayed to send an empty message after a specified number of milliseconds
Sendmessagedelayed specify the number of milliseconds after which the message is sent
Working principle:
Several components that work with handler:
· Message handler objects that are received and processed
· MessageQueue Message Queuing, which is a FIFO-first way to manage a message, managed by Looper
· Looper Each thread can have only one Looper, manage Message Queuing, and constantly take messages out of the message queue and divide the messages into corresponding handler processing.
Steps:
1. Call Looper's prepare () method to create a Looper object for the current thread, and the construction method will create a companion message queue
2. Create an instance of the handler subclass and override the Handlemessage () method, which is responsible for handling messages from other threads.
3. Call Looper's Loop method to start Looper.
Flow of messaging mechanisms:
Example: A child thread computes data from 1+2+3+4+......+5000 and passes it to the main thread to display it on the interface
Public class handleractivity extends Activity{ PrivateTextView Mtvresult;PrivateHandler Handler;protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_handler); Mtvresult = (TextView) Findviewbyid (R.id.tv_result); GetResult (); Handler =NewHandler () { Public void Handlemessage(Message msg) {Super. Handlemessage (msg);if(Msg.what = =0x1) {Mtvresult.settext (Msg.getdata (). GetString ("Result","0")); } } }; } Public void GetResult() {NewThread (NewRunnable () { Public void Run() {Message msg =NewMessage (); Msg.what =0x1;intsum =0; for(inti =1; I <= the; i++) {sum + = i; } Bundle Bundle =NewBundle (); Bundle.putstring ("Result", integer.tostring (sum)); Msg.setdata (bundle); Handler.sendmessage (msg); }}). Start (); }}
Copyright notice: Just out of the original content of the pot, I hope you have help ~
------handler message passing mechanism