[Android] Introduction to Android messaging mechanism

In the previous section, first put the part accessing the network into a sub thread for execution. New thread() {}. Start(), which is directly implemented by anonymous internal classes, overrides the run() method, and the internal classes access external variables, which should be defined as final.

Only the original thread that created can touch XXXXX. Only the main thread can access the view object because of the synchronization and mutual exclusion of threads

When implementing the update interface internally, a check is made to check whether the update operation is executed in the UI thread. If there is no problem, if not, a runtime exception is thrown, calledfromwrongthreadexception

In the previous section, after accessing the network in the sub thread, we directly called setimagebitmap() of the ImageView object to modify the UI interface, so an error will be reported

We need to tell the main thread a message in the sub thread. We need to modify the interface, pass the content bitmap to the main thread and ask him to modify it for us.

The child thread sends a message through the handle, and the message is placed in the message queue,

There is a poller for looper messages in the main thread

If the poller finds a new message, it calls handlemessage () of the handle object to process the message

Handler is a message processor and must be new in the main thread

Define the handler in the member attribute of the main thread, and directly override the handlemessage () method of the new handler anonymously

In the sub thread, call the SendMessage (MSG) method of the handler object to put the message into the message queue. Parameters: MSG is the message object, new comes out the message object, set the what attribute of the message object = a custom int constant, and set the obj attribute of the message object = the content to be delivered.

In the rewriting method of handlermessage of the main thread, this message object will be obtained. Judge the what attribute, call the setimagebitmap () method of ImageView object, and put the obj attribute of message object in it.

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
分享
二维码
< <上一篇
下一篇>>