How to update the UI using multiple threads in Android
In Android, time-consuming operations should be placed in sub-threads, or ANR may be left blank. This time we will learn how to update the UI using multiple threads in Android. First, let's take a look at anr: application not reponse: why the application has no response to the main thread: UI thread anr: the main thread needs to do a lot of important things and respond to click events, update the ui. If the main thread is blocked for too long, the application will not respond. To prevent anr from occurring in the application, all time-consuming operations should be executed in the Child thread. After learning about anr, we will learn how to enable multithreading and update the ui in Android. There are two methods: Handler. Handler gets the logoff object in the current thread. logoff is used to retrieve the Message from the Message Queue containing the message, and then Handler distributes and processes the message. Principle of handler: android provides handler and logoff to satisfy the communication between threads. Handler first-in-first-out principle. Logoff is used to manage message Exchange between objects in a specific thread ). 1) loue: A thread can generate a loue object to manage the message queue (message queue) in this thread. 2) handler: you can construct a handler object to communicate with logoff so as to push new messages to messagequeue, or receive messages sent by logoff (extracted from messagequeue. When we use it, we need to define the message in the Child thread and pass the obj object to be returned to msg. At the same time, because handler not only needs to process this type, therefore, we need to define what type for handler classification. Message msg = new Message (); msg. what = CHANGE_UI; msg. obj = result; handler. sendMessage (msg); Okay, next we will use handler for the instance. New Thread () {public void run () {try {URL url = new URL (path); HttpURLConnection conn = (HttpURLConnection) url. openConnection (); conn. setRequestMethod ("GET"); conn. setConnectTimeout (5000); conn. setRequestProperty ("User-Agent", ""); int code = conn. getResponseCode (); if (code = 200) {InputStream is = conn. getInputStream (); String result = StreamTools. readInputStream (is); // TV _content.setText (resul T); 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 block e. printStackTrace (); Message msg = new Message (); msg. what = ERROR; handler. sendMessage (msg );}};}. start (); StreamTools used here. the implementation of readInputStream is as follows: String. /*** Convert the input stream to a String * @ param is * @ return */public static String readInputStream (InputStream is) {try {ByteArrayOutputStream baos = 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 to parse 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 block e. printStackTrace (); return "failed to get";} Where hand Ler's implementation is like this. Private Handler handler = new Handler () {public void handleMessage (android. OS. message msg) {switch (msg. what) {case ERROR: Toast. makeText (MainActivity. this, "failed to get data", 0 ). show (); break; case CHANGE_UI: TV _content.setText (msg. obj + ""); Toast. makeText (MainActivity. this, "failed to get data", 0 ). show (); break ;};}; in this case, we can use handler, that is, the message processor, to update the UI. The second method is used. RunOnUiThread (new Runnable () is used. To implement Runnable, we can directly update the UI in this thread. Is the method provided by the api, which is more convenient. New Thread () {@ Override public void run () {final String result = LoginServices. loginByGet (username, password); if (result! = Null) {// runOnUiThread (new Runnable () {@ Override public void run () {// TODO Auto-generated method stub Toast. makeText (MainActivity. this, result, 0 ). show () ;}}) ;}else {// request failed runOnUiThread (new Runnable () {@ Override public void run () {// TODO Auto-generated method stub Toast. makeText (MainActivity. this, "request failed", 0 ). show ();}});}};}. start ();