Basics-Updating UI elements in a non-UI thread

Source: Internet
Author: User
Tags message queue

Personal original, reproduced please specify the source: http://blog.csdn.net/supluo/article/details/


Understand the two concepts first

1, Ui:user interface abbreviation, the user interface meaning. You can not properly understand the things that we can see and manipulate, what is called the UI in Android, and can be easily understood as elements such as view and its subclasses. This is not the right concept, just a beginner to make a simple.

2, Anr:application not responding, meaning that the program does not respond.

In the following cases, Android will report a ANR error:

– The main thread ("Event processing Thread"/"UI thread") does not respond to input events within 5 seconds

–broadcastreceiver did not complete the return within 10 seconds

As a result, time-consuming operations are usually performed in other threads to prevent the program from stalling or even having a ANR error, and then manipulating the UI elements after the thread has finished executing.

The following example causes the lag, executing the following code in a button:

            Prodialog.show ();//Show progress dialog Box            System.Threading.Thread.Sleep (10 * 1000);//thread sleeps 10 seconds, simulates time-consuming operation, triggers ANR            handleresult ( "Data Update succeeded:" + new Random (). Next (10)); Update other UI elements
The above code will block the main UI thread, in fact, the dialog box will not be displayed, the dialog box will not appear immediately after the call show method, the reader to discuss their own, so the above effect is particularly bad, only show the effect of the button is pressed, after 10 seconds to update the UI, the dialog box will not be displayed, So the right thing to do is to display a dialog box, put the time-consuming action on the other thread, and then update the UI after the execution is done, but we can't update the UI element directly in other threads, so the topic of this article is how to update the UI elements in a non-UI thread.

Get down to the chase.

During normal development, we often need to open other threads to execute the more time-consuming operations encountered in the program, in case the main UI thread is blocked from causing the ANR error, but in the actual development process, you may encounter the following two exception information

1. Only the original thread, created a view hierarchy can touch its views;

2, Can ' t create handler inside thread that have not called looper.prepare ();

The first way to update a UI element in a non-UI thread is to cause this error, and the second is to display some UI hint information in a non-UI thread, which can be generalized to be caused by updating the UI in a non-UI thread. Let's take a look at the following two error examples:

A non-UI thread updates the UI element (in one button event, the event binding code is not posted)

New Thread (() =            {                try                {                    mtext.text = "Data Update succeeded:" + new Random (). Next (ten);                }                catch (Exception ex)                {                }            }). Start ();

Execution result throws Android.view.viewrootimpl$calledfromwrongthreadexception:only the original thread that created a view hierarchy can touch its views. That is the case of the first error message mentioned above.

Second, UI prompts are not UI threads. (The event binding code is not affixed when you do the following in a button event)

New Thread (() =            {                try                {                    prodialog.show ();//prodialog is a dialog                }                catch (Exception ex)                {                }            }). Start ();
execution result throws Java.lang.RuntimeException:Can ' t create handler inside thread that have not called looper.prepare (), That is the case of the second error message mentioned above.

Workaround:

This error for the developers to contact this line, often this problem, in fact, this problem is quite simple and easy to solve, but the most important thing is to find the most appropriate solution, the following is a few more simple solutions.

1. Entrusted type

To delegate a part of a non-UI element that performs UI operations to the main UI thread, see the following code:

        Prodialog.show ();            New Thread (() =            {                System.Threading.Thread.Sleep (*);                This. Runonuithread (() =//this refers to the activity object, Runonuithread is a member of the activity method                {                    handleresult ("Data Update succeeded:" + new Random (). Next ());})            . Start ();

2. View.post form

Use the Post or Postdelay method of the UI element

Official documentation Note: Causes the Runnable to is added to themessage queue. The runnable'll be run on the user interface thread.

Parameters:action the Runnable that'll be executed.

Returns:returns true if the Runnable is successfully placed in to the message queue. Returns false on failure, usually because the Looper processing the message queue is exiting.

Examples are shown in the following code:

Prodialog.show ();            New Thread (() =            {                try                {                    System.Threading.Thread.Sleep];                    Mtext.post (() =                    {                        handleresult ("Data Update succeeded:" + new Random (). Next (Ten));}                    );                catch (Exception ex)                {this                    . Runonuithread (                        () =                        {                            Toast.maketext (this, "there was an error during thread execution! ", Toastlength.long). Show ();})                    ;                }            ). Start ();
This method includes the Postdelay method, which is very similar to the first method, and the underlying implementation is essentially the same.


3. Handler Form

1), initialize a handler object

Handler mhandler;//Defining variables

Mhandler = new Handler (handlemessage);//initialization, where anonymous functions can be used, etc.

method definition, which is primarily the update UI action

private void Handlemessage (Message msg)          {            switch (msg. What) {case                 1:                    handleresult ("Data Update succeeded:" + new Random (). Next (Ten));                    break;            }        }

2), at the right time, use handler to send messages for UI updates

            Prodialog.show ();            New Thread (() =            {                System.Threading.Thread.Sleep (*);                Mhandler.sendemptymessage (1);            }). Start ();
The specific use of handler can consult the relevant information to further understand.

Most of the above methods use the handler to do message processing, the following gives a handler work diagram,


4. Asynctask form

Asynctask, which is a lightweight asynchronous class provided by Android, can inherit Asynctask directly, implementing asynchronous operations in the class , and provides interface feedback for the current the degree of asynchronous execution (UI Progress updates can be implemented through an interface), and finally feedback is performed to the UI main thread.

This code a bit more, can self-check Baidu, there are quite a lot of good articles to borrow.

A little reminder that In Xamarin.android, if the execution parameter passed to Asynctask is a string, it needs to be wrapped with Java.Lang.String, and the earlier version I tested was needed to do, and the most recent version didn't have time to test, and later I made up the part, or I knew I could communicate.

These are the more commonly used methods.

Demo


Personal made a blog app, usually a toilet, before bedtime and so casually read two articles, always have some harvest, I hope you support! http://blog.csdn.net/supluo/article/details/43489475

Basics-Updating UI elements in a non-UI thread

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.