Simple examples of handler and message in Android

Simple examples of handler and message in Android

preface:

Although I have learned the asynctask of Android to realize the processing of a message. However, in the learning of Android, we often see the use of handler and message in some demos, so it is necessary to learn handler and message. As for how much to learn, the author still adheres to his own view, "how much to use, how much to learn". After all, there are such convenient things as asynctask, and handler and message are not so indispensable. (it doesn't take much time to understand this article simply)

This example updates the content of textview in handler. Novice readers may ask why not solve it directly in oncreate? It's mainly about requirements. If we need to get content from the Internet in the sub thread and update it to textview, it's unreasonable to write it directly in the main thread. However, because this example is mainly a reference and makes it more understandable to novices, there is no code to obtain content from the network. (you cannot update the UI directly in the child thread, and the program will crash)

Previous rendering:

They are the effects before and after clicking the button

OK, let's look at the concept and code directly:

Message:

Message is a message passed between threads. It can carry a small amount of information internally for data exchange between different threads. In addition to the what field, the arge1 and arg2 fields can also be used to carry some integer data, and the obj field can be used to carry an object object.

Handler

As the name suggests, handler means handler. It is mainly used to send and process messages. Sending a message usually uses the handler's SendMessage () method. After a series of tossing and turning, the sent message will eventually be delivered to the handler's handlemessage () method.

MainActivity:

activity_ main:

The above is the use of handler and message in Android. If you have any questions, please leave a message or communicate and discuss with the community of this site. 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
分享
二维码
< <上一篇
下一篇>>