Classic summary of Handler in Android development

Source: Internet
Author: User

When the application starts, Android first opens a main thread (that is, the UI thread), and the main thread is the UI control in the admin interface for event distribution.

AD:

First, the definition of handler:

Mainly accepts the data sent by the child thread, and updates the UI with this data in conjunction with the main thread.

Explanation: When the application starts, Android first opens a main thread (that is, the UI thread), the main thread is the UI control in the management interface for event distribution, for example, if you click on a button, Android will distribute the event to the button to respond to your action.  If you need a time-consuming operation at this time, for example: network read data, or read a large local file, you can not put these operations in the main thread, if you put in the main thread, the interface will appear suspended animation, if 5 seconds has not been completed, you will receive an Android system error message  Force Close. This time we need to put these time-consuming operations on a sub-thread, because the child threads involve UI updates, the Android main thread is not secure, that is, the update UI can only be updated in the main thread, and the operations in the child threads are dangerous. By this time, Handler appeared. To solve this complex problem, because handler is running in the mainline approached (UI thread), it and the child thread can pass the data through the Message object, at this time, the handler undertakes to accept the child thread passed over (the child thread uses the Sedmessage () method to pass the younger brother) The Message object, which contains data, is placed in the main thread queue and updated with the main thread.

Ii. Some features of handler

Handler can distribute the Message object and the Runnable object into the main thread, each handler instance is bound to create his line approached (typically in the main thread), and it has two functions:

(1) Arranging messages or runnable to be executed somewhere in a main thread;

(2) Schedule an action to be executed in a different thread.

Some ways to distribute messages in handler

Post (Runnable)

Postattime (Runnable,long)

Postdelayed (Runnable Long)

Sendemptymessage (int)

SendMessage (Message)

Sendmessageattime (Message,long)

Sendmessagedelayed (Message,long)

The Post class method above allows you to arrange a runnable object into the main thread queue,

The SendMessage class method allows you to schedule a message object with data to queue and wait for updates.

Iii. examples of Handler

Subclasses need to inherit the Hendler class and override the Handlemessage (Message msg) method to accept thread data.

The following is an instance that implements the function of modifying the contents of the interface button through a thread

  1. Public class Myhandleractivity extends Activity {
  2. Button button;
  3. MyHandler MyHandler;
  4. protected void OnCreate (Bundle savedinstancestate) {
  5. Super. OnCreate (savedinstancestate);
  6. Setcontentview (R. Layout Handlertest);
  7. Button = (button) Findviewbyid (R. Id. button);
  8. MyHandler = new MyHandler ();
  9. //When a new handler instance is created, it is bound to the current thread and message queue to begin distributing data
  10. //Handler has two functions, (1): Timed execution of message and Runnalbe object
  11. //(2): Let an action be executed in a different thread.
  12. //It arranges messages, using the following methods
  13. //Post (Runnable)
  14. //Postattime (Runnable,long)
  15. //postdelayed (Runnable,long)
  16. //sendemptymessage (int)
  17. //SendMessage (Message);
  18. //Sendmessageattime (Message,long)
  19. //sendmessagedelayed (Message,long)
  20. //The above method starts with post allowing you to process the Runnable object
  21. //sendmessage () allows you to process a Message object (the message can contain data)
  22. MyThread m = new MyThread ();
  23. new Thread (m). Start ();
  24. }
  25. /** 
  26. * Accept messages, process messages, and this handler will run with the current main thread
  27. * */
  28. class MyHandler extends Handler {
  29. Public MyHandler () {
  30. }
  31. Public MyHandler (Looper L) {
  32. super (L);
  33. }
  34. //Subclasses must override this method to accept data
  35. @Override
  36. public void Handlemessage (Message msg) {
  37. //TODO auto-generated method stub
  38. Log. D ("MyHandler", "Handlemessage ... "); 
  39. Super. Handlemessage (msg);
  40. //The UI can be updated here
  41. Bundle B = Msg. GetData ();
  42. String color = b. GetString ("color");
  43. Myhandleractivity. This . button Append (color);
  44. }
  45. }
  46. class MyThread implements Runnable {
  47. public Void Run () {
  48. try {
  49. Thread. Sleep (10000);
  50. } catch (Interruptedexception e) {
  51. //TODO auto-generated catch block
  52. E. Printstacktrace ();
  53. }
  54. Log. D ("thread .....") ", " Mthread ... "); 
  55. Message msg = new Message ();
  56. Bundle B = new bundle (); Storing Data
  57. B. Putstring ("Color", "my");
  58. Msg SetData (b);
  59. Myhandleractivity. This . MyHandler. SendMessage (msg); //Send messages to handler, update UI
  60. }
  61. }
  62. }

Classic summary of Handler in Android development

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.