Multithreaded programming in Android (iii) How handler updates the UI

Source: Internet
Author: User

Handler how and why to update the UI and the problems encountered

1. Mode:

The UI can only be updated with handler.

The code is as follows:

 PackageCom.chengdong.su.handlerdemo;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.os.HandlerThread;ImportAndroid.os.Message;ImportAndroid.util.Log;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button;ImportAndroid.widget.TextView;/** * How to update the UI in Android * * @author SCD * */ Public  class sixactivity extends Activity {    PrivateString TAG = GetClass (). Getsimplename ();PrivateString Mname ="Handlerthread";PrivateTextView MView;/** The object of the Handler * *    PrivateHandler Mhandler =NewHandler () { Public void Handlemessage(Message msg) {LOG.D (TAG,"------>handlemessage () Main thread:"+ Thread.CurrentThread ()); Mview.settext ("Main thread");    }; };@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main);        Init (); LOG.D (TAG,"------>oncreate () Main thread:"+ Thread.CurrentThread ());NewThread () { Public void Run() {Try{Thread.Sleep ( -); LOG.D (TAG,"------>thread () Child thread:"+ Thread.CurrentThread ());//UpdateUI01 ();                    //updateUI02 ();                    //updateUI03 ();UpdateUI04 (); }Catch(Interruptedexception e)                {E.printstacktrace ();        }            };    }.start (); }/** * Init the view * *    Private void Init() {MView = (TextView) Findviewbyid (R.ID.TEXTVIEW1); }/** * How to update the UI 1 */     Public void updateUI01() {LOG.D (TAG,"------>updateui01 () thread () Child thread:"+ Thread.CurrentThread ()); Mhandler.post (NewRunnable () {@Override             Public void Run() {LOG.D (TAG,"------>updateui01 () thread () run () Main thread:"+ Thread.CurrentThread ()); Mview.settext ("Main thread");    }        }); }/** * How to update the UI 2 */     Public void updateUI02() {LOG.D (TAG,"------>updateui02 () thread () Child thread:"+ Thread.CurrentThread ()); Mhandler.sendemptymessage (0); }/** * How to update the UI 3 */     Public void updateUI03() {LOG.D (TAG,"------>updateui03 () thread () Child thread:"+ Thread.CurrentThread ());//Update components in the UI interfaceRunonuithread (NewRunnable () {@Override             Public void Run() {LOG.D (TAG,"------>updateui03 () thread () run () Main thread:"+ Thread.CurrentThread ()); Mview.settext ("Main thread");    }        }); }/** * How to update the UI 4 */     Public void updateUI04() {LOG.D (TAG,"------>updateui04 () thread () Child thread:"+ Thread.CurrentThread ()); Mview.post (NewRunnable () {@Override             Public void Run() {LOG.D (TAG,"------>updateui04 () thread () run () Main thread:"+ Thread.CurrentThread ()); Mview.settext ("Main thread");    }        }); }}

It is recommended to use the first and second types.

2. Reasons for updating the UI with handler:

Updating the UI throws an exception if the current thread and the thread are not equal.
The activity checks whether the current thread and the main threads are equal before the Onresume () method starts.
So in the newly opened thread, if you do not hibernate directly update the UI, you will not throw an exception.
If you hibernate and then do the update UI operation, an exception will be thrown.

Examples are as follows: (Do not use this, just for illustrative purposes)

@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main);        Init (); LOG.D (TAG,"------>oncreate () Main thread:"+ Thread.CurrentThread ());NewThread () { Public void Run() {//No exception occurs                //Mview.settext ("Main thread");                Try{Thread.Sleep ( -);//Exception occurredMview.settext ("Main thread"); }Catch(Interruptedexception e)                {E.printstacktrace ();        }            };    }.start (); }

3. Problems encountered with handler in Android development:

1. You cannot update the UI in a child thread.
2. If the child thread creates a handler, be sure to create a Looper object: Looper.prepare ();

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Multithreaded programming in Android (iii) How handler updates 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.