Android Learning Note: handler Preliminary

Source: Internet
Author: User

Handler

  Handler, which inherits directly from object, a Handler allows the sending and processing of a message or Runnable object and is associated to the MessageQueue of the main thread. Each handler has a separate thread and is associated to a thread of Message queuing, meaning that a handler has an intrinsic message queue. When an handler is instantiated, it is hosted on a thread and message queue thread, which handler messages or runnable into the message queue and extracts messages or runnable from the message queue to manipulate them.


is a simple example. Two buttons are for testing purposes only. When you click the button, the TextView text is changed.

package com.jam.testhandler;import android.app.activity;import android.os.bundle;import  android.os.handler;import android.os.message;import android.util.log;import android.view.view; import android.view.view.onclicklistener;import android.widget.button;import  android.widget.textview;public class mainactivity extends activity {private  button button1;private button button2;private textview textview;private  myhandler handler; @Overrideprotected  void oncreate (bundle savedinstancestate)  { Super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main);handler = new  MyHandler ();button1 =  (button)  findviewbyid (r.id.button1);button2 =  (button)   Findviewbyid (R.id.button2);textview =  (TextView)  findviewbyid (R.id.textview); Button1.setonclicklistener (New onclicklistener ()  {@Overridepublic &NBsp;void onclick (VIEW V)  {thread t = new myworkthread (); T.start ();}); Button2.setonclicklistener (New onclicklistener ()  {@Overridepublic  void onclick (View v )  {testthread tt = new testthread (); Thread thread = new thread (TT); Thread.Start ();});} Method of integrating Thread private class myworkthread extends thread {@Overridepublic  void  run ()  {try {thread.sleep (2000);}  catch  (interruptedexception e)  {e.printstacktrace ();} string s =  "String from work thread";//Here I don't understand the difference between obtainmessage and new message. Message msg = handler.obtainmessage (); Message msg = new message (); Msg.obj = s;handler.sendmessage (msg);}} Implement runnable//Note that Runnable represents the thread body instead of a thread private class testthread implements runnable {@ Overridepublic void run ()  {runnable  r = new runnable ()  {@Overridepublic  void run ()  {system.out.println (" Thread's name--" + thread.currentthread (). GetName ());}}; Handler.post (R);}}}

After Handler sends a message to the queue, Looper gets it back to the Handler that sent the message.

Handler got it, in this case, because handler is in the main thread, this mechanism can be processed by other threads to get to the handler, and then modify the UI.


Here's another way to use handler in a new thread

Package com.example.testhandler2;import android.app.activity;import android.os.bundle;import  android.os.Handler;import android.os.Looper;import android.os.Message;import  android.util.log;import android.view.view;import android.view.view.onclicklistener;import  Android.widget.button;import android.widget.textview;public class mainactivity extends  activity {private button button;private textview textview;private handler  handler; @Overrideprotected  void oncreate (bundle savedinstancestate)  {super.oncreate ( savedinstancestate) Setcontentview (r.layout.activity_main);button =  (button)  findviewbyid ( R.id.button);textview =  (TextView)  findviewbyid (R.id.textview); Button.setonclicklistener (new  onclicklistener ()  {@Overridepublic  void onclick (view v)  {Message msg  = new message (); msg.what =&nBsp;50;handler.sendmessage (msg);}}); Workerthread workerthread = new workerthread (); Workerthread.start ();} private class workerthread extends thread {@Overridepublic  void run ()   {Looper.prepare (); Handler = new handler ()  {@Overridepublic  void handlemessage ( message msg)  {log.d ("msg",  ""  + msg.what);}}; Looper.loop ();}}  }

After clicking the button, use handler to send the data and take the data out of the other thread.


when a child thread is created using the Handler be aware of the fixed usage:

Prepare first Loop

Looper.prepare ()

Replication Handler the method Handlemessage

Looper.loop


Attention:

Thread represents a thread

Runnable represents the thread body is not a thread , thread body incoming thread to use

Handler on which thread is generated , Looper on which thread

  handler.post () method will be a Runnable put message callback Span lang= "ZH-CN" style= "font-size:11pt;" xml:lang= "ZH-CN" and then incoming Message Queuing.

LoopRemove withRunnableof theMessageafter,determine if there isCallbackProperties,There is the executionhandlecallback (Message msg),then execute in this methodRunMethod,NoNewaThread,In this run () method, it is common to write operations that need to be on the UI thread.


With such a mechanism can compensate for the absence of the statement block of defects. (OC language)


In addition, there are two times very good blog posts about handler:

android--Multi-Thread handler

Android threads are used to update the UI----thread, Handler, Looper, TimerTask, etc.

Android Learning Note: handler Preliminary

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.