Android Learning Note 48: Updating the UI in real time with handler

Source: Internet
Author: User

In Android, the MessageQueue, Looper, and handler three classes are primarily implemented to implement message processing for Android applications. Where the MessageQueue class is used to describe Message Queuing, the Looper class is used to create message queues, and to enter the message loop, and the handler class is used to send messages and receive messages.

This article will be a brief introduction to handler and a simple example of how to use handler to update the UI in real time.

The role of 1.Handler

In Android, when an application starts, the Android system launches a main thread (also known as a UI thread) that is used primarily to manage UI controls in the interface and to respond to user actions in real time. If we do a very time-consuming operation in the UI thread, such as clicking on the button to upload or download a file, then there will be suspended animation (not responding to user actions) during this time, which is obviously a very poor user experience. What's more, if the time-consuming operation is not over in 5 seconds, the Android system will "force shutdown" by mistake.

Therefore, it is common practice to start a child thread and then perform these relatively time-consuming operations in a child thread. But what if we want to update the UI in a child thread?

Because in Android, the update UI can only be done in the main thread, so in order to update the UI in a child thread, it is necessary for the child thread to notify the main thread and then the main thread to update the UI.

This process is achieved through handler.

Child threads can communicate with handler in two ways: message and runnable. Using the message, you can pass some parameters from the child thread to the main thread, handler get the information and handle it accordingly. Using runnable, you can perform a processing result directly. In fact, the essence of both is to put the content in the handler queue, handler will process a message or finish a process before the next step, so that there will not be multiple threads simultaneously require UI processing and cause confusion.

Common methods of 2.Handler

The contents of the handler message queue (message or runnable) can be set to execute immediately, deferred for a certain time, or specified at some point. In addition, you can specify that it be placed on the head of the queue, indicating that the content has the highest priority and executes immediately.

The settings for these requirements can be implemented 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);

(6) SendMessage (Message msg);

(7) Sendmessageattime (Message msg, long Uptimemillis);

(8) sendmessagedelayed (Message msg, long Uptimemillis);

(9) Sendmessageatfrontofqueue (Runnable R);

3. Example

In this example, we create a Web project that is simple, just to get the current time of the system and then show it.

Run the Web project on Tomcat to see the effect of the 1 shown.

Figure 1 Web project Run effect

This page is implemented by a simple date.jsp file.

All we have to do now is to display the contents of the current page through a TextView in the Android project, and in the child thread every 1 seconds, send a message to Handler,handler to finish refreshing the UI after receiving a message notification.

Here is the concrete implementation of each step.

3.1 Starting a child thread in the main thread

First of all, we need to start a sub-thread in the main thread, this is relatively simple, directly in the Mainactivity OnCreate () method called the following method:

New Thread (mrunnable). Start ();

3.2 Send a message to handler in a child thread

We used the Runnable interface object Mrunnable When we created the sub-thread. Here, you only need to implement the Runnable interface and override the run () method of the interface, which is implemented in the run () method to send a message to handler every 1 seconds. The implementation method is as follows:

1/*     2      * Function   :   Implement the Run () method, send a message every 1 seconds to handler 3      * Author     :   Blog Park-still indifferent 4 */      5     private Runnable mrunnable = new Runnable () {6 Public         void Run () {7 while             (true) {8                 try {9                     Thr Ead.sleep (+),                     mhandler.sendmessage (Mhandler.obtainmessage ()), one                 } catch (Interruptedexception e) {                     e.printstacktrace ();                 }14             }15         }16     };

3.3Handler Receive message notification

Finally, we create a handler object to receive the message notification. After you receive the message notification, complete the refresh UI. The implementation method is as follows:

1     /* 2      * Function   :   Implement Handlemessage () method to receive message, Refresh UI 3      * Author     :   Blog Park-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 Refreshing the UI

As can be seen from the above code, the action of refreshing the UI is done in the Refreshui () method. The implementation of the Refreshui () method is also simple, call the getInputStream () method in the Httputils tool class, get the page content input stream for the Web project shown in Figure 1, and then flow the input into a string and display it in the TextView control. The implementation method is as follows:

1/*     2      * Function   :   Refresh UI 3      * Author     :   Blog Park-still indifferent 4      *     /5 private void Refreshui () {6< C9/>try {7             InputStream InputStream = Httputils.getinputstream (); 8             String resultdata = Httputils.getresultdata (InputStream); 9             Mtextview.settext (resultdata);         catch (IOException e) {             e.printstacktrace ();         }13     }

3.5 Instance Effect

Finally, run the Android project, run effect 2, you can see that the current time every 1 seconds will be refreshed, can always keep the page as shown in Figure 1 time synchronization.

Figure 2 Running effect

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.