2 ways to update the UI interface for child threads

Source: Internet
Author: User
Tags stub

In general, we will do some time-consuming operations on the child threads.

1, Android message mechanism:

2, Knowledge points:

Message: Messages that contain the message ID, the message Processing object, and the processed data are queued by MessageQueue and processed by handler.
Handler: Handler, responsible for sending and processing the message. When using handler, you need to implement the Handlemessage (Message msg) method to process a specific message, such as updating the UI.
MessageQueue: Message Queuing, which holds messages sent by handler and executes according to FIFO rules. Of course, storing a message is not a meaningful preservation, but rather a concatenation of the message in the form of a linked list, waiting for the looper to be extracted.
Looper: The message pump continuously extracts message execution from the MessageQueue. Therefore, a MessageQueue needs a looper.
Thread: Threads that are responsible for dispatching the entire message loop, that is, the execution site of the message loop.

Child Threads Update UI interface method One: with handler

1, we will be in the case of the previous Asynctask operation, we will click the call event in the previous call method comment.

 Public classMainactivityextendsActivity {PrivateSimpleadapter sa; PrivateButton btn; PrivateTextView TV; PrivateList<userinfos> list=NewArraylist<userinfos>(); PrivateBaseadapter Adapter; PrivateListView LV; PrivateRunnable DoInBackground1; PrivateRunnable DoInBackground2; PrivateRunnable DoInBackground3; PrivateHandler Handler; PrivateThread th; PrivateThread Th2; @Overrideprotected voidonCreate (Bundle savedinstancestate) {//here is the main thread of the UI        Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main);  for(inti = 0; I < 5; i++) {Userinfos u=NewUserinfos (); U.setname ("Xiao Ming" +i); U.setsex ("Male" +i);        List.add (U); } LV= (ListView) This. Findviewbyid (R.id.listview1); TV=(TextView) Findviewbyid (R.ID.TEXTVIEW1); BTN=(Button) Findviewbyid (R.id.button1); Btn.setonclicklistener (NewOnclicklistener () {//analog data access generates data@Override Public voidOnClick (View v) {//TODO auto-generated Method Stub                /*Take tk=new take (mainactivity.this);//Sync Task Tk.execute (list,adapter);//parameter is passed to Doinbackground*/               thread t1=new thread (DOINBACKGROUND1);                T1.start ();                Thread t2=new thread (DOINBACKGROUND2);                T2.start ();                Thread t3=new thread (DOINBACKGROUND3); T3.start ();            }});
Handler=NewHandler () { Public voidhandlemessage (android.os.Message msg) {intwhat=Msg.what; LOG.I ("Handler", "has received the message, message what:" +what+ ", ID:" +Thread.CurrentThread (). GetId ()); if(what==1) {log.i ("Handler has received the message", "" +what ); Tv.settext ("Child Thread One"); }                     if(what==2) {log.i ("Handler has received the message", "" +what );                                             Adapter.notifydatasetchanged (); }                     if(what==3) {log.i ("Handler has received the message", "" +what );                         Adapter.notifydatasetchanged (); Btn.settext ("Child thread Three");             }                 }; };             //Child thread One            doinbackground1=new Runnable () {@Override public void run () {//TOD                    O auto-generated Method Stub try {thread.sleep (3000);                        } catch (Interruptedexception e) { //TODO auto-generated catch block                    E.printstacktrace (); }1. Access to the database or the Internet, not the UI process, so no cardmessage Msg=new message ();An identification number for the message, which makes it easy for handler to recognizemsg.what=1;                    Handler.sendmessage (msg); LOG.I ("DD", "sub-line Cheng has sent a message to handler");}}; Sub-thread TwoDoinbackground2=new Runnable () {@Override public void run () {                        TODO auto-generated Method Stub try {thread.sleep (5000);                            } catch (Interruptedexception e) {//TODO auto-generated catch block                        E.printstacktrace ();                        } message Mge=new message ();                        mge.what=2;                         Handler.sendmessagedelayed (mge,200);                         for (Userinfos us:list) {us.setname ("Lili");                                        } log.i ("DD", "sub-line Cheng sent a message to handler"); }};//Sub-line ChengDoinbackground3=new Runnable () {@Override public void Ru                                N () {//TODO auto-generated method stub try {                            Thread.Sleep (9000);                                } catch (Interruptedexception e) {//TODO auto-generated catch block                            E.printstacktrace ();                            } message Mge=new message ();                            mge.what=3;                             Handler.sendmessagedelayed (mge,200);                             for (Userinfos us:list) {us.setsex ("female");                                                    } log.i ("DD", "sub-line Cheng sent a message to handler"); }};

1, the child thread sends the message, notifies handler to complete the UI update:

2, Handler the Handlemessage method carries on the message processing, receives the message to carry on the UI interface update.

Note: The handler object of method one must be defined in the main thread, and if multiple classes are called directly to each other, it is not very convenient to pass a Content object or call through an interface.

Child thread Update UI interface method Two: update with the Runonuithread method of the Activity object

UI Update via the Runonuithread method

 Public void OnClick (View v) {                //  TODO auto-generated method stub/                *taketk=new Take (mainactivity.this);//Synchronous Task                Tk.execute (list,adapter);//parameter is passed to Doinbackground*                / /*thread t1=new thread (DOINBACKGROUND1);                T1.start ();                Thread t2=new thread (DOINBACKGROUND2);                T2.start ();                Thread t3=new thread (DOINBACKGROUND3);                T3.start (); */                 Th.start ();                Th2.start ();            }});
Th=NewThread () {@Override Public voidrun () {//Here is the time-consuming operation, updating the UI after completion;Runonuithread (NewRunnable () {//Update UI@Override Public voidrun () {//TODO auto-generated Method StubBtn.settext ("Runonuithread Child thread One");                    }                                            }); Super. Run ();             }             }; Th2=NewThread () { Public voidrun () {Runonuithread (NewRunnable () {@Override Public voidrun () {Try{Thread.Sleep (3000); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }                            //TODO auto-generated Method StubTv.settext ("Runonuithread sub-thread Two");                 }                                              });                              }; };

1, through the Runonuithread method new a runnable implementation of the Run method UI interface update.

If it is in a non-contextual class (Activity), it can be invoked by passing the context;

Chip

2 ways to update the UI interface for child threads

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.