Several methods of using asynchronous threads to update UI view in Android

In Android, sub threads cannot update UI.

So we need to dynamically change the UI view in other ways,

1、runOnUiThread

Activity provides a lightweight method to update the UI. When the fragment needs to be used, use getactivity.runonuithread to start the thread

This method is the simplest and convenient to update some notifications that do not need to be judged, such as dynamically obtaining the number of unread messages in chat items.

2、Handler message

Using this method, you can set the control of button countdown, which is also a common method to update the UI.

Create a main thread to receive messages continuously sent by sub threads, and judge the type of messages delivered through msg.what. Update the related UI according to the type.

Create a thread to receive:

Method of sending message:

3、Handler Runnable

You also need to create a thread first.

Use postdelayed to set the load delay at the beginning of the load

Or we need to perform an automatic refresh action. When the action is completed, the refresh effect will be hidden

4、AsyncTask

Asynctask makes it easier to use UI threads. This class allows you to perform background operations and update views on UI threads without manipulating threads and handlers.

Asynctask is designed as an auxiliary class thread, handler, and does not constitute a general threading framework. Used for short update operations.

When using, you need to inherit asynctask and rewrite the method:

Doinbackground: used to return results

Onprogressupdate: onprogressupdate is executed in the UI thread. All users can operate on the UI space

Onpostexecute: receive the return result of doinbackground and use it to update the UI

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

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