Several ways and insights for Android to update the UI

Source: Internet
Author: User
Tags sendmsg

"The World in the Code "

Describe your Android learning path with text notes

  reprint please retain source by Qiao http://blog.csdn.net/qiaoidea/article/details/45115047

1. Brief description

Put on a first one of the most error-prone errors we've had when we're doing Android development Androidruntimeexception : "Only theoriginal thread, that created a view Hierarchy can touch its views "
The reason for this is that when we make changes to the UI, Android checks whether our current operating thread is the UI thread, not the exception that is reported. (See the Checkthread method for the Viewrootimpl class).

2. The Programme

So how do we update the UI, which is briefly used and handler. The concept is outlined first: Adroid creates a uithread thread at run time that controls the display, update, and control interaction of the UI interface. Other threads push the message events (messages) such as update logic to the message queue (MESSAGEQUEUE) of the main thread through handler, and finally, the main thread processes the message events (Handlemessage) in order to update and control the interface.
This article focuses on how to update the UI and how to use it, and please follow the [Android update UI advanced][1]in the context of the update process.
Among them, the commonly used methods are briefly summarized as follows:
-Handler.sendmessage ();
-Handler.post ();
-Can be runonuithread () in activity;
-Can be View.post () in Sub view

In fact, the following methods of the entire process of processing logic is based on the first, encapsulated into a message event object sent to the queue and ordered to process it, but the android to us encapsulated the method.

3. Practice3.1 handler.senmessage () + handler.dispatchmessage ()

The handler of the main thread is defined in the activity (the child thread can also define handler, which of course requires the message pump looper to rotation), and implements the DispatchMessage method to process the message object. The object is to encapsulate the content into a message after the child-threading logic is complete and send the message through Handler.senmessage ().
Example code:
A. First define the code logic for changing the UI handler and DispatchMessage methods

     /** * Bring result data with message Change UI * First define the main thread handler and update the data method * *    Private Static Final intUpdate_title =0;//Update title flag    PrivateHandler mainhandler=NewHandler () { Public void DispatchMessage(Android.os.Message msg) {if(Msg.what = = Update_title) {String title = Msg.getdata (). GetString ("Result");            Titleview.settext (title); }Else{//Other messages}        }; };

B. Parts of data that need to be processed, such as some time-consuming operations that are executed in a child thread, and then called Handler.senmessage ()

NewThread () {@Override             Public void Run() {//Your processing logic, here simple sleep one second                 This. Sleep ( +);//Notification update UI                //message msg = new Message ();                //We can use the construct method to create a message, but we should use Message.obtain () to get an empty message object from the message pool for memory-saving resourcesMessage msg = Mainhandler.obtainmessage ();                    Msg.what = Update_title; Bundle bundle =NewBundle ();//Message data entityBundle.putstring ("Result","Sendmsg--result"); Msg.setdata (bundle);//mainhandler.sendmessage (msg);                    //If you are using Message.obtain () we can directlyMsg.sendtotarget (); }}.start ();

This Message object is mentioned here (see [Android Update UI advanced][1] for more details)

Parameters that can be used to pass data:

    • int what;
    • int arg1;
    • int arg2;
    • Object obj;
    • Bundle data;

Used for callbacks.

    • Runnable callback;

Usually to make the code logic look clearer and easier to understand, I prefer to update the UI (scenario 2/3/4) by passing the callback callback directly. For scenario one, you can simply optimize to
Directly define Handler

privatenew Handler();

Send Message

NewThread () {@Override             Public void Run() {Try{//Your processing logic, here simple sleep one second                     This. Sleep ( +);//using obtainmsg = Message.obtain (MainHandler,NewRunnable () {@Override                         Public void Run() {Titleview.settext ("Sendmsg--result");                    }                    });                Msg.sendtotarget (); }Catch(Interruptedexception e)                {E.printstacktrace (); }}}.start ();
3.2 Handler.post ()

The second approach to scenario one can be simplified to

     NewThread () {@Override             Public void Run() {Try{//Your processing logic, here simple sleep one second                     This. Sleep ( +); Mainhandler.post (NewRunnable () {@Override                         Public void Run() {//Your processing logicTitleview.settext ("Postrunnable--result");                }                    }); }Catch(Interruptedexception e)                {E.printstacktrace (); }}}.start ();
3.3 Runonuithread ()

For the above scenario, the activity can be further simplified, without the new handler object, call the Runonuithread () method directly

         /** * Use activity's Runonuithread * /        NewThread () {@Override             Public void Run() {Try{//Your processing logic, here simple sleep one second                     This. Sleep ( +); Runonuithread (NewRunnable () {@Override                         Public void Run() {Titleview.settext ("Runonuithread--result");                }                    }); }Catch(Interruptedexception e)                {E.printstacktrace (); }}}.start ();
3.4 View.post ()

Of course, if you have a child view or a custom view, you can use the View.post () method directly after processing the logic

NewThread () {@Override             Public void Run() {Try{//Your processing logic, here simple sleep one second                     This. Sleep ( +); Viewpostbtn.post (NewRunnable () {@Override                         Public void Run() {Titleview.settext ("Viewpost--result");                }                    }); }Catch(Interruptedexception e)                {E.printstacktrace (); }}}.start ();

In summary, the update view looks less difficult to use.
Finally, attach the source code file.
Click to download the source code

Several ways and insights for Android to update the UI

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.