How Android multithreading updates the UI

Source: Internet
Author: User

Android, for time-consuming operations to be placed in sub-threads, otherwise it will rest their lives anr, this time we will learn how the Android multi-threaded update UI.

First, let's Meet the ANR:

  ANR: Application not reponse: application unresponsive
  main thread: UI thread
  the cause of the ANR : The main thread needs to do a lot of important things, respond to click Events, update the UI, if the main thread block time too long, the application will be unresponsive, in order to avoid the application of ANR, all the time-consuming operation should be placed in the child thread execution.

After we met the ANR, we came to learn how to turn on multi-threading under Android and update the UI. A total of two ways:

The first adoption: Handler.

Handler gets the Looper object in the current thread, Looper is used to remove the message from the message queue that contains the message, and the handler to distribute and process the message.

handler principle of the system :

  Android provides handler and Looper to meet the communication between threads. Handler first-out principle. Looper is used to manage the exchange of messages (message exchange) between objects within a particular thread.

1) Looper: A thread can produce a Looper object that manages the message queue of this line thread

2) Handler: You can construct a handler object to communicate with Looper in order to push new messages into the MessageQueue, or to receive messages sent from Looper (removed from MessageQueue).

When we use it, we need to define the message in the child thread and pass the Obj object that we want to return to the MSG, and since handler not only deal with this type, we also define what type, so that the handler can be sorted.

Message msg = new Message (); msg.what = Change_ui;msg.obj = Result;handler.sendmessage (msg);

Okay, so let's use handler for example.

   New Thread () {public   void run () {   try {URL url = new URL (path); HttpURLConnection conn = (httpurlconnection) url.openconnection (); Conn.setrequestmethod ("GET"); Conn.setconnecttimeout (Conn.setrequestproperty) ("User-agent", "" "); int code = Conn.getresponsecode (); if (code== () {InputStream is = Conn.getinputstream (); String result = Streamtools.readinputstream (is);//tv_content.settext (result); Message msg = new Message (); msg.what = Change_ui;msg.obj = Result;handler.sendmessage (msg);} Else{message msg = new Message (); msg.what = Error;handler.sendmessage (msg);}} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace (); Message msg = new Message (); msg.what = Error;handler.sendmessage (msg);}         };   }. Start ();

The implementation of the Streamtools.readinputstream used here is such that the input is converted to a string.

/** * Translate input into String * @param is * @return */public static string Readinputstream (InputStream is) {try {Bytearrayoutputstream B AOS = new Bytearrayoutputstream (); int len = 0;byte[] buffer = new Byte[1024];while (len = is.read (buffer))!=-1) {Baos.write (Buffer,0,len);} Is.close (); Baos.close (); byte[] result = Baos.tobytearray ();//try parsing the string returned by the URL, String temp = new string (result); if ( Temp.contains ("Utf-8")) {return temp;} else if (Temp.contains ("GBK")) {return new String (result, "GBK");} return Temp;//return new String (result); catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace (); return "Get Failed";}}

One of the handler implementations is this.

Private Handler Handler = new Handler () {public void Handlemessage (android.os.Message msg) {switch (msg.what) {case Error:t Oast.maketext (Mainactivity.this, "Get Data Failed", 0). Show (); Break;case CHANGE_UI:tv_content.setText (msg.obj+ ""); Toast.maketext (Mainactivity.this, "Get Data Failed", 0). Show (); break;}};};

So we can update the UI with handler, which is the message handling mechanism,

The second way.

With Runonuithread (new Runnable ()), this is to implement the Runnable excuse that we can update the UI directly in this thread. Is the method provided by the API, more convenient.

  

New Thread () {    @Override public    void Run () {    final String result = Loginservices.loginbyget (username, password);    if (result = null) {    //Success    Runonuithread (new Runnable () {@Overridepublic void Run () {//TODO auto-generated method Stubtoast.maketext (mainactivity.this, result, 0). Show ();}});    else{    //Request failed    Runonuithread (new Runnable () {@Overridepublic void Run () {//TODO auto-generated method Stubtoast.maketext (Mainactivity.this, "request Failed", 0). Show ();}});}}        ;    }. Start ();

  

How Android multithreading updates the UI

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.