Handler realizes the communication between threads, downloads files and dynamically updates the progress bar

1. Principle

Each thread corresponds to a message queue, messagequeue, which realizes the communication between threads. You can load the data into the message through the handler object, and then add the message to the message queue, and then the thread will process the messages in the message queue in turn.

2. Message

Initialization: generally, the message. Obtain () method is used to obtain a message object. This method will check whether there are reusable objects in the message object pool. If not, a new object will be created.

What: equivalent to the identifier of message, which is different from other messages.

Arg1, arg2: int type, can pass integer.

Obj: object type, which can pass any object.

3. Send message

In the sub thread, the handler. SendMessage (MSG) of the main thread can be called to send messages. After a series of method calls, the handler's handlemessage method will be triggered for message processing.

Main methods of sending messages:

The difference between sendmessageattime() and sendmessagedelayed() is that the former sends messages at a specified time and can be used in conjunction with systemclock. Uptimemillis(); The latter is to delay sending messages.

In addition to the sendmessage() method, you can also send a message through the post() method:

Difference between sendmessage() and post(): https://www.oudahe.com/p/24591/

4. Memory leakage

https://www.oudahe.com/p/24590/

5. Dynamically update the progress bar by downloading files through the handler object

Androidmanifest join permission statement:

Layout:

Activity:

summary

The above is what Xiaobian introduced to you. The handler realizes the communication between threads, downloads files, and dynamically updates the progress bar. I hope it will be helpful to you. If you have any questions, please leave me a message, and Xiaobian will reply to you in time. Thank you very much for your support for the programming tips website!

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