Android Hnadler, Message, Looper

Source: Internet
Author: User

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

Why do you use handler?

Many of our mobile phone functions or operations can not be placed in the activity, such as downloading files, processing large amounts of data, complex error operations and so on. If you put it in the activity (that is, the main thread), there will be a long time not responding, and even the ANR and other errors (that is, 5 seconds did not respond), which will result in a poor user experience, so this shows the necessity of handler. The user experience is greatly improved if we put the time-consuming and laborious operations into another thread operation, so that we can synchronize operations with the main thread (UI) threads without long-awaited or unresponsive operations. Handler is one thing that implements the above function.

A

Let's start with a simple example to illustrate the basic use of handler:

1, first create a handler object, you can directly use the handler parameterless constructor to create the handler object,

2. In the listener, call handler's Post method to add the thread object that will be executed to the thread queue. This will add the thread object to the handler

3. The operation to be performed writes the Run method of the thread object, which is generally a runnable object, where the Run method is replicated.

Run:

After we click the Starthandler button, the output box will output a start every three seconds until we click the Endhandler button, and the information in the output box will not be output.

Main code:

 1 public class Mainactivity extends Activity {2 3 private Button Mstartbutton,mendbutton; 4 @Override 5 public void OnCreate (Bundle savedinstancestate) {6 super.oncreate (savedinstancestate); 7 Setcontentview ( R.layout.activity_main); 8 Mstartbutton = (Button) Findviewbyid (R.id.start); 9 Mendbutton = (Button) Findviewbyid (r.id.end); Mstartbutton.setonclicklistener (New Startbutto Nlistener ()); Mendbutton.setonclicklistener (new Endbuttonlistener ());}14 Private Class STARTBU Ttonlistener implements onclicklistener{16 @Override17 public void OnClick (View v) {18//immediate thread Objects are added to the handler message queue, which is a first-in-one-out data structure that executes the run () method after the thread object is removed from the message queue. Handler.post (runnable),}21}22 Private class Endbuttonlistener implements Onclicklistene        r{23 @Override24 public void OnClick (View v) {25/* will remove runnable this thread object from handler message queue, 26     There will be no runnable this thread object in the message queue, and the run () method will not be executed */27 handler.removecallbacks (runnable); 28}29}30 Create a Handler object, each Handler has a message queue associated with it Handler Handler = new Handler (); 32//action to be performed write to the Run () method of the Thread object, and then Runnab Le runnable = new runnable () {@Override35 public void run () {System.out.println ("start")         ; 37//Delay 3000 milliseconds Add the thread object to the message queue, add it every 3000 milliseconds, and cycle through the handler.postdelayed (runnable, 3000); 39 }40};41}

Two

The following is the effect of using handler to implement a ProgressBar automatic update:

Run:

When we click on the Starthandler button, ProgressBar will update itself, adding the same units per second.

1. First create a handler object, inherit the handler class, and override the Handlemessage method to create the handler object.
2. In the listener, call handler's Post method to add the thread object that will be executed to the thread queue. The thread object is added to the thread queue of the handler object.
3. The operation to be performed writes the Run method of the thread object, which is generally a runnable object, where the Run method is replicated.
The handler contains two queues, one of which is the thread queue and the other is Message Queuing. Using the Post method puts the thread object into the thread queue of the handler, using SendMessage (Message message) to place the message in the message queue.
If you want this process to be executed, you can execute the postdelayed or POST method inside the Run method, and then add the thread object to the message queue and repeat. If you want the thread to stop executing, call the Removecallbacks (Runnable R) method of the handler object to remove the thread object from the thread queue and cause the thread to stop executing.

Handler provides an asynchronous message processing mechanism for Android that returns immediately after a message is sent to the message queue (sendMessage) and blocks when a message is read from the message queue, where the public in handler is executed when the message is read from the message queue The Void Handlemessage (Message msg) method, so you should use an anonymous inner class to override the method when you create the handler, write a read-to-message operation in the method, and use Handler's obtainmessage () to obtain the message object.

Main code:

 1 public class Mainactivity extends Activity {2 3 private Button Mstartbutton = null; 4 private ProgressBar MPr Ogressbar = null; 5 private int i=0;         6 @Override 7 public void OnCreate (Bundle savedinstancestate) {8 super.oncreate (savedinstancestate); 9         Setcontentview (r.layout.activity_main); Mstartbutton = (Button) Findviewbyid (R.id.start); 12 Mprogressbar = (ProgressBar) Findviewbyid (R.id.progressbar), Mstartbutton.setonclicklistener (New S  Tartlistener ());}16 public class Startlistener implements ONCLICKLISTENER{17 @Override18 public void OnClick (View arg0) {handler.post (runnable),}21}22 Handler handler = new Handler ()             {@Override24 public void Handlemessage (Message msg) {super.handlemessage (msg); 26 Mprogressbar.setprogress (MSG.ARG1), Handler.post (runnable), if (msg.arg1==100) {handler.removecallbacks (runnable); mprogressbar.setprogress (0); 31 Handler.post (runnable); i=0;33}34}35};36 runnable runnable = new Runna ble () {PNS @Override38 public void Run () {i+10;40 i = *. Message message = handler.                 Obtainmessage (); 41//Set the value of the parameter of the message object to i42 Message.arg1 = i;43 try {44 Thread.Sleep (interruptedexception e) {//TODO auto-generated catch bloc K47 e.printstacktrace ();}49 if (i==100) {Handler.removecallbac          KS (runnable); mprogressbar.setprogress (0);}53 handler.sendmessage (message); 54 }55};56}

Three

Handler the relationship to the thread:
After the Runnable object is placed in the handler thread queue using the handler post method, the execution of the runnable does not actually open the thread separately, but is still executed in the current activity thread. Handler just invokes the run method of the Runnable object.

Let's use an example to prove that we use the ID of the print thread to prove that they are actually running on the same thread.

Run:

If in the code we use:

Thread thread = new Thread (runnable);
Thread.Start ();

This way the thread's ID and name will be different when the thread is started, run as follows:

The main code is as follows:

 1 public class Mainactivity extends Activity {2 Handler Handler = new Handler (), 3 @Override 4 public void O          Ncreate (Bundle savedinstancestate) {5 super.oncreate (savedinstancestate); 6//handler.post (runnable); 7 8 Setcontentview (R.layout.activity_main); 9 Thread thread = new Thread (runnable), Thread.Start (), System.out.println ("id============:" +t Hread.currentthread (). GetId ()), System.out.println ("NAME:" +thread.currentthread (). GetName ());}14 Runn Able runnable = new runnable () {@Override16 public void run () {System.out.println ("Runab LEID::::::::::: "+thread.currentthread (). GetId ()); System.out.println (" Runablename: "+thread.currentthread (). g                 Etname ()), try {Thread.Sleep (10000), and catch (Interruptedexception e) {22 TODO auto-generated catch block23 e.printstacktrace ();24}25}26};27} 

Four

We pass the data through a message and finally print out the data we passed in the Handlemessage () method.

What bundles are:
Bundle is a special map, which is a tool for passing information, whose keys can only be of type string, and the value can only be a common basic data type.
How to get handler to open a new thread when executing runnable:
1. First generate a Handlerthread object that implements the function of using looper to handle Message Queuing, which is provided by the Android application framework
Handlerthread handlerthread = new Handlerthread ("Handler_thread");
2, before using the Handlerthread Getlooper () method, you must first call the class start (); Handlerthread.start ();
3, according to this Handlerthread object to get the Looper object. 4. Create a custom subclass that inherits from the handler class, where a parameter is constructed for the Looper object, and the content of the method invokes the constructor of the parent class.
5. Using the Looper object obtained in step three to create the object of the custom handler subclass, and then send the message to the handler message queue, handler the replication Handlemessage () will execute to process the message in the message queue.

messages, the Message object, can pass some information, you can use Arg1.arg2,object to pass some shaping or objects, and you can use the SetData of the Message object (bundle bundle) In other words, the bundle object is passed to the newly created thread, and the newly created thread can extract the bundle object from the message using GetData () when executing handlemessage (message msg) for processing.

Perform:

Main code:

 1 public class Mainactivity extends Activity {2 3 @Override 4 public void OnCreate (Bundle savedinstancestate) { 5 super.oncreate (savedinstancestate); 6 Setcontentview (R.layout.activity_main); 7 System.out.println ("Activity------------->" + thread.currentthread (). GetId ()); 8 9 Handlerthread Handlerthread = new Handlerthread ("Handlerthread"); 10//Handlerthread in use Getlop The per () method must call the start () method of the class first, or the null pointer is Handlerthread.start (); MyHandler MyHandler = new Myhandl ER (Handlerthread.getlooper ()); Message message = Myhandler.obtainmessage (); 15//MSG is sent to the target object, the so-called target object is the generation The handler object of the MSG object is bundle bundle = new Bundle (), Bundle.putint ("Age", "at"), and Bundle.putstring ("N Ame "," Gaojicai "); Message.setdata (bundle); Message.sendtotarget ();}23 PU       Blic class MyHandler extends handler{25-public MyHandler () {27      Super ();}29 public MyHandler (Looper Looper) {A super (Looper); 31 32             }33 @Override35 public void Handlemessage (Message msg) {super.handlemessage (msg); 37 Bundle bundle = Msg.getdata (); int = Bundle.getint ("Age");             . getString ("name"); System.out.println ("Age---->" +age+ ", name------->" +name "); 41 42 System.out.println ("Handler------------->" + thread.currentthread (). GetId ()); System.out.println ("Hand Lemessage "); 44}45}46}

All Project code: http://download.csdn.net/detail/gaojiecaiandroid/5430585

Android Hnadler, Message, Looper

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.