Android handler example

Source: Internet
Author: User
The handler class has two main functions:
  • Send messages in a new thread
  • Obtain and process messages in the main thread

The above statement is very simple. It seems that you only need to divide it into two steps: Send a message in the newly started thread, and then obtain and process the message in the main thread. But this process involves a question: when will the newly started thread send messages?

When will the main thread obtain and process messages? This time is obviously difficult to control.(Handler is an asynchronous message mechanism)

In order to make the main thread "timely" handle the information sent by the newly started thread, it is clear that it can only be implemented through callback-Developers only need to re-process messages in the handler class, when a newly started thread sends a message, the method for processing the message in the handler class is automatically called back.

The handler class contains the following methods for sending and processing messages.

  • Void handlemessage (Message MSG): method for processing messages. This method is usually used for rewriting.
  • Final Boolean hasmessages (INT what): Check whether the message queue contains a message with the value of what.
  • Final Boolean hasmessages (INT what, object): checks whether the message queue contains messages with the "what" attribute as the specified value and the "object" attribute as the specified object.
  • Multiple overloaded messge obtainmessage (): gets messages.
  • Sendemptymessage (INT what): sends an empty message.
  • Final Boolean sendemptymessagedelayed (INT what, long delaymillis): specify how many milliseconds to send an empty message
  • Final Boolean sendmessage (Message MSG): sends the message immediately.
  • Final Boolean sendmessagedelayed (Message MSG, long delaymillis): after the specified number of millisecondsSend message

With the above methods, the program can easily use handler to transmit messages.

The keywords Android. OS. Handler involve many knowledge points. I will list some keywords below to introduce handler:
  • Android. OS. Handler, Android. OS. handler. Callback
  • Logoff,
  • Threadle, runnable
  • Message, message
    Queue
Android. OS. Handler handler is responsible for sending and processing messages in Android. Its main purposes include: 1) send messages as planned or execute a runnanble (using the POST method); 2) put messages sent from other threads into the message queue, by default, Handler accepts the message loop instances under the current thread (using handler (loggle), handler (loggle, Handler. callback callback) can specify a thread). At the same time, a message queue can be distributed and processed by multiple objects in the current thread (in the UI thread, the system has an activity to process, you can initiate several handler operations ). When handler is instantiated, logoff can be any thread. As long as there is a handler pointer, any thread can also sendmessage. Handler does not process messages concurrently. One Logoff
The next message is read only after processing a message. Therefore, the processing of the message is in the form of a blocking (handlemessage () method, and time-consuming operations can be placed in other threads for execution, after the operation, send a message (via the sendmessges method), and then update the UI by handlemessage ). Start ~ End example

Main. xml

<? XML version = "1.0" encoding = "UTF-8"?> <Br/> <linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" <br/> Android: layout_width = "fill_parent" <br/> Android: layout_height = "fill_parent" <br/> Android: Orientation = "vertical"> </P> <p> <button <br/> Android: id = "@ + ID/startbutton" <br/> Android: layout_width = "fill_parent" <br/> Android: layout_height = "wrap_content" <br/> Android: TEXT = "start" <br/> <button <br/> Android: Id = "@ + ID/endbutton" <br/> Android: layout_width = "fill_parent" <br/> Android: layout_height = "wrap_content" <br/> Android: TEXT = "end" <br/> </P> <p> </linearlayout>

Interface Diagram


Handlertestactivity. Java

Public class handlertestactivity extends activity {</P> <p> // declare two button controls <br/> private button startbutton = NULL; <br/> private button endbutton = NULL; <br/> @ override <br/> Public void oncreate (bundle savedinstancestate) {<br/> super. oncreate (savedinstancestate); <br/> setcontentview (R. layout. main); <br/> // obtain the object representing the Control Based on the Control ID, and set the listener for the two buttons <br/> startbutton = (button) findviewbyid (R. id. startbutton); <br/> startbutton. setonclicklistener (New startbuttonlistener (); <br/> endbutton = (button) findviewbyid (R. id. endbutton); <br/> endbutton. setonclicklistener (New endbuttonlistener (); <br/>}< br/> class startbuttonlistener implements onclicklistener {</P> <p> Public void onclick (view V) {<br/> // call the post method of handler and add the thread object to be executed to the queue. <br/> handler. post (updatethread); <br/>}</P> <p> class endbuttonlistener implements onclicklistener {<br/> Public void onclick (view V) {<br/> handler. removecallbacks (updatethread); <br/>}< br/> // create a handler object <br/> handler = new handler (); <br/> // write the executed operation in the run method of the thread object <br/> runnable updatethread = new runnable () {</P> <p> Public void run () {<br/> system. out. println ("updatethread"); <br/> // inside the run method, execute the postdelayed or POST method <br/> handler. postdelayed (updatethread, 3000); // The message is added to the queue After 3000 milliseconds, and postdelayed is added to the Message Queue <br/>}< br/> }; </P> <p>}

Click Start and print every 3 seconds without clicking end.

References: Message Mechanism of Android learning notes, asynchronous and multithreading android
Handler

Android
Open-source project-standuptimer learning notes Index

More references http://www.cnblogs.com/keyindex/articles/1822463.html

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.