Use Handler to update UI in real time
In Android, the message processing of Android applications is mainly realized through three classes: MessageQueue, Looper and Handler. Among them, the MessageQueue class is used to describe the message queue; the Looper class is used to create a message queue and enter the message loop; the Handler class is used to send and receive messages.
This article will mainly give a brief introduction to Handler, and use a simple example to demonstrate how to use Handler to update the UI in real time.
1. The role of Handler
In Android, when an application starts, the Android system starts a main thread (also called UI thread), which is mainly used to manage UI controls in the interface and respond to user operations in real time. If we perform a very time-consuming operation in the UI thread, such as clicking the Button button to upload or download files, the interface will appear suspended animation (does not respond to user operations) during this time, which is obviously an extreme user experience. Poor. More seriously, if this time-consuming operation is not over within 5 seconds, the Android system will give an error prompt "Force Close".
So the usual practice is to start a child thread, and then complete these time-consuming operations in the child thread. But what if we want to update the UI in a child thread?
Because in Android, updating the UI can only be done in the main thread, so if you want to update the UI in the sub-thread, you must have the sub-thread notify the main thread, and then the main thread will update the UI.
This process is achieved through Handler.
Child threads can communicate with Handler in two ways: Message and Runnable. Using Message, you can pass some parameters from the child thread to the main thread, and the Handler obtains this information and handles it accordingly. Using Runnable can directly execute a processing result. In fact, the essence of the two is to put content in the queue of the Handler. The Handler will process a message or perform a certain process before proceeding to the next operation, so that there will be no multiple threads requesting UI processing at the same time. causing confusion.
2. Common methods of Handler
The contents of the Handler's message queue (Message or Runnable) can be set to be executed immediately, delayed for a certain period of time, or specified to be executed at a certain time. In addition, you can also specify that it is placed at the head of the queue, indicating that the content has the highest priority and is executed immediately.
The setting of these requirements can be achieved by some of the following functions:
(1)post(Runnable r);
(2)postAtTime(Runnable r, long uptimeMillis);
(3)postDelayed(Runnable r, long uptimeMillis);
(4)postAtFrontOfQueue(Runnable r);
(5)sendEmptyMessage(int what);
(6)sendMessage(Message msg);
(7)sendMessageAtTime(Message msg, long uptimeMillis);
(8)sendMessageDelayed(Message msg, long uptimeMillis);
(9)sendMessageAtFrontOfQueue(Runnable r);
3. Examples
In this example, we created a web project, which is very simple, just get the current time of the system and display it.
Run the Web project on Tomcat, you can see the running effect shown in Figure 1.
Figure 1 Web project running effect
The page is implemented with a simple date.jsp file.
What we have to do now is to display the content of the current page through a TextView in the Android project, and send a Message to the Handler every 1 second in the child thread. After the Handler receives the Message notification, the UI refresh is completed. operate.
The specific implementation of each step is described below.
3.1 Start a child thread in the main thread
First of all, we need to start a sub-thread in the main thread, which is relatively simple, just call the following method directly in the onCreate() method of MainActivity:
new Thread(mRunnable).start();
3.2 Send Message to Handler in child thread
When creating a child thread, we use the Runnable interface object mRunnable. Here, you only need to implement the Runnable interface, rewrite the run() method of the interface, and send a Message to the Handler every 1 second in the run() method. The specific implementation method is as follows:
1 /* 2 * Function : Implement the run() method and send a Message to the Handler every 1 second 3 * Author : Blog Garden - still indifferent 4 */ 5 private Runnable mRunnable = new Runnable() { 6 public void run() { 7 while ( true ) { 8 try { 9 Thread.sleep(1000 ); 10 mHandler.sendMessage(mHandler.obtainMessage()); 11 } catch (InterruptedException e) { 12 e.printStackTrace (); 13 } 14 } 15 } 16 };
3.3Handler receives Message notification
Finally, we create a Handler object to receive Message notifications. After receiving the Message notification, you can complete the operation of refreshing the UI. The specific implementation method is as follows:
1 /* 2 * Function : Implement the handleMessage() method to receive Message and refresh the UI 3 * Author : Blog Garden - still indifferent 4 */ 5 private Handler mHandler = new Handler() { 6 public void handleMessage(Message msg) { 7 super .handleMessage(msg); 8 refreshUI(); 9 } 10 };
3.4 Renewal UI
As can be seen from the above code, the operation of refreshing the UI is done in the refreshUI() method. The implementation of the refreshUI() method is also very simple. Call the getInputStream() method in the HttpUtils tool class to obtain the input stream of the page content of the Web project shown in Figure 1, and then convert the input stream into a string and put it into the TextView control. Display it. The specific implementation method is as follows:
1 /* 2 * Function : Refresh UI 3 * Author : Blog Garden - still calm 4 */ 5 private void refreshUI() { 6 try { 7 InputStream inputStream = HttpUtils.getInputStream(); 8 String resultData = HttpUtils.getResultData(inputStream ); 9 mTextView.setText(resultData); 10 } catch (IOException e) { 11 e.printStackTrace(); 12 } 13 }
3.5 Instance effect
Finally, run the Android project, and the running effect is shown in Figure 2. It can be seen that the current time will be refreshed every 1 second, which can always be synchronized with the time of the page shown in Figure 1.
Figure 2 Running effect