Analysis of android neutron thread UI update Methods

Source: Internet
Author: User

Analysis of android neutron thread UI update Methods
I. Why do I write this article?

?? Do you often see many books saying: You cannot operate the ui in a child thread, or an error will be reported. Have you also encountered the following questions (see the following code ):

@Override      protected void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.activity_main);          tv = (TextView) findViewById(R.id.tv);          Thread.currentThread().setName("UIThread");          new LooperThread().start();      }      private class LooperThread extends Thread {          @Override          public void run() {              Thread.currentThread().setName("OtherThread");              tv.setText("other thread");          }      }  

?? The above is indeed operating the ui in the Child thread, but it does not report an error. Why? Isn't that exactly the same as what I mentioned in the book? At that time, I also encountered this problem. So with this blog, I would like to thank those elders on the Internet for their selfless sharing. Now I have recorded my thoughts and thoughts.

II. Introduction

?? During Android development, you often need to update the UI of the interface. The UI is updated by the main thread, that is, the UI thread. If the page is directly updated in a thread other than the main thread, an error is often reported. Thrown exception: android. view. ViewRoot $ CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. How can this problem be solved? Next I will detail how the sub-thread updates the ui:

3. method 1 for updating the UI using the sub-Thread

?? Define Handler in the main thread, send messages to the subthread, and notify Handler to complete UI update.

MHandler = new Handler () {@ Override public void handleMessage (Message msg) {// operation interface myText. setText (information from the network); super. handleMessage (msg) ;}}; public class MyThread extends Thread {public void run (){? ? ? // Time-consuming operations? ? ? ? LoadNetWork (); Message msg = new Message (); mHandler. sendMessage (msg); // send a Message to Handler ,}}

The principle of handler is as follows:

2. Update with runOnUiThread

?? This is the best practice. You can use the following method to refresh the page.

New Thread () {public void run () {// this operation is time-consuming. After completion, the UI is updated. runOnUiThread (new Runnable () {@ Override public void run () {// update the UI imageView. setImageBitmap (bitmap );}});}}. start ();

?? This method is flexible, but if the Thread is defined elsewhere, the Activity object needs to be passed (passed through the constructor ).

3. View. post (Runnable r)

?? Method explanation: derive your subclass from Runnable and overload the run () method. Call View. post (myRunnableObj) to add your Runnable object to the UI thread for running.

Public void onClick (View v) {new Thread (new Runnable () {public void run () {// time-consuming operation? ? ? ? ? ? LoadNetWork ();? MyText. (new Runnable () {myText. setText (information from the network) ;}}}). start ();}

?? This method is simpler, but you need to pass the View to be updated. Note: The post function transmits a runnable interface (You know that runnable is not a thread. You must be separated from the thread ).

4. Use asynchronous tasks
// Execute new downloadimagetask(cmd.exe cute ("www.91dota.com") in the UI thread; private class DownloadImageTask extends AsyncTask {protected String doInBackground (String... url) {return loadDataFormNetwork (url [0]); // time-consuming operation in the background} protected void onPostExecute (String result) {myText. setText (result); // get the information from the network to refresh the page }}

For background tasks, such as download tasks, AsyncTask is required. If you need to pass status values and other information, such as socket connections in Bluetooth programming, you need to use the status values to prompt the connection status and perform corresponding processing, you need to use Handler + Thread; you need to open another thread to process data to avoid blocking UI threads, such as IO operations or loops. You can use Activity. runOnUiThread (); if you only want to update the UI without multithreading, use View. post () is enough. 4. The illusion of updating the UI in the Child thread

?? Back to the problem at the beginning, the sub-thread successfully updated the ui. Another method is wrong: use interface callback in the Child thread to update the ui in the activity. In fact, this method also updates the UI in the Child thread in disguise. Why did it succeed? The reason is refined: this exception is thrown by the detection settings in the android source code. If the detection method is not executed, no error will be reported. In the onCreate method, when a thread is enabled to update the UI, no error is reported because the view has not yet been released and the invalidate method has not been called.

For more information, see:

Http://www.bkjia.com/kf/201111/111172.html
Http://blog.csdn.net/imyfriend/article/details/6877959
Http://doc.okbase.net/aigestudio/archive/127460.html
Http://blog.csdn.net/zhaokaiqiang1992/article/details/43410351
Http://blog.csdn.net/aigestudio/article/details/43449123
Http://javapolo.iteye.com/blog/1343583
Http://blog.csdn.net/androidzhaoxiaogang/article/details/8136222

V. Summary

?? Sometimes, using sub-threads to directly update the ui does not report errors, but this is not recommended. google's android underlying code will detect the thread that updates the ui, the reason is to avoid directly updating the ui in a non-ui thread. Check for two aspects: 1. Whether the ui is updated. The method for updating the view in android is invalidate. 2. Whether the current thread is a ui thread during the update. Although we do not report exceptions, this is not a good method. The reason for the design of google is that the UI thread is more purely engaged in interface operations. If time-consuming operations are performed on the ui thread, you may feel stuck when performing UI operations. That is to say, from the perspective of update View, it is better to use the UI thread, neither the UI thread nor the UI cannot be updated.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.