Explain several methods of Android UI update in detail
Foreword
In Android development, the update of interface UI is completed in the main thread. Threads are divided into main thread (MT) and work thread (WT). We usually perform some time-consuming operations in WT, such as download, network, cache, etc., and then send the results to MT for UI update. If the UI is updated in WT, an exception will be thrown. Android.view.viewroot $calledfromwrong threadexception: only the original thread that created a view hierarchy can touch its views.
In BT search, WiFi search and other UI processes that need to update the view, many use broadcast to notify the search results and display them in listview in real time for UI update. The following methods are usually used to update the UI: handler, runonuithread, and the sub thread sends a message.
1、 Activity.runonuithread
Use activity.runonuithread (runnable) to create the code to update the UI in runnable, and then pass the runnable object to activity.runonuithread (runnable) when the UI needs to be updated. In this way, runnable objects can be called in the UI program. If the current thread is a UI thread, the action is executed immediately. If the current thread is not a UI thread, the operation is a UI thread published to the event queue.
2、 Handler.post (runnable)
3、 The child thread sends a message
First, add the following code where you need to perform the update
Then enter the handler for processing
The above three methods can update the UI. Which method depends on the superposition degree in the code, but I recommend method 1. I hope it will help you in your study, and I also hope you can support programming tips.