Android study note 48: Use handler to update the UI in real time

Source: Internet
Author: User

In Android, Android applications are implemented mainly through messagequeue, logoff, and handler.Program. Among them, the messagequeue class is used to describe the Message Queue; The logoff class is used to create the message queue and enter the message loop; the handler class is used to send and receive messages.

This document briefly introduces handler and uses a simple example to demonstrate how to use handler to update the UI in real time.

 

1. Functions of handler

In Android, when an application is started, the android system starts a main thread (also known as the UI thread), which is mainly used to manage the 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 to upload or download files, in this period, the interface will be suspended (not responding to user operations), which is obviously a poor user experience. More seriously, if the time-consuming operation in five seconds has not been completed, the android system will send an error message "Force disable ".

Therefore, the common practice is to start a subthread and complete these time-consuming operations in the subthread. But what should we do if we want to update the UI in the Child thread?

In Android, the UI update can only be performed in the main thread. to update the UI in the sub-thread, the sub-thread must notify the main thread and then update the UI.

This process is implemented by handler.

The sub-thread can communicate with handler in two ways: Message and runnable. Message can be used to pass some parameters from the Child thread to the main thread. handler gets the information and processes it accordingly. You can use runnable to directly execute a processing result. In fact, the two are actually put content in the handler queue. handler will process a message or execute a processing before proceeding to the next step, in this way, there will be no confusion caused by simultaneous UI processing by multiple threads.

 

2. Common handler Methods

The content (message or runnable) in the handler Message Queue can be set to immediate execution, and the execution can be delayed for a certain period of time or specified at a certain time point. In addition, you can also place the content in the queue header, indicating that the content has the highest priority and is executed immediately.

You can use the following functions to set these requirements:

(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. Instance

In this example, we created a web project, which is very simple. It only obtains the current time of the system and then displays it.

Run the WEB Project on Tomcat and you can see the running effect shown in 1.

Figure 1 WEB Project Running Effect

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

What we need to do now is to display the content of the current page through a textview In the android project, and send a message to handler every one second in the Child thread, handler completes the UI refresh operation after receiving the Message notification.

The specific implementation of each step is described below.

3.1 start a subthread in the main thread

First, we need to start a subthread in the main thread. This is relatively simple. You can directly call the following method in the oncreate () method of mainactivity:

NewThread (mrunnable). Start ();

3.2 send a message to handler in the Child thread

When creating a sub-thread, we used the runnable interface object mrunnable. Here, you only need to implement the runnable interface and rewrite the run () method of this interface. In the run () method, you can send a message to handler every 1 second. The specific implementation method is as follows:

 1       /*  2   * Function: implements the run () method. A message is sent to handler every 1 second.  3   * Author: blog Park-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 notifications

Finally, we create a handler object to receive message notifications. After receiving the Message notification, refresh the UI. The specific implementation method is as follows:

 1       /*  2   * Function: implements the handlemessage () method to receive messages and refresh the 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 refresh the UI

FromCodeWe can see that the operations to refresh the UI are completed 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 page content input stream of the web project shown in figure 1, and then convert the input stream to a string, enter the textview Control for display. The specific implementation method is as follows:

 1       /*  2   * Function: refresh the UI.  3   * Author: blog Park-still indifferent  4        */  5       Private   Void  Refreshui (){ 6           Try  {  7 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 Effects

Finally, run the android project. The running effect 2 shows that the current time is refreshed every one second, and the time synchronization with the page shown in Figure 1 is always maintained.

 

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.