Android Application Software Development (10) handler usage

Source: Internet
Author: User

Use handler to manage threads

Steps:

1. Apply for a handler object

Handler handler = new handler ();

2. Create a thread

{Inherit the Thread class or implement the runnable interface}

Use runnable to create an internal anonymous Class Object updatethread (to re-write the run method)

3. Add the thread to the thread queue using the POST method of handler

Handler. Post (updatethread );

4. Use the removecallbacks method of handler to remove the updatethread thread

Note: If the thread is executed from the thread queue, there will be no threads in the queue.

Therefore, if a thread cannot add it to the queue after execution, removecallbacks is not required.

There are two scenarios for a thread to exit the thread queue:

One is executed, and the run method must be executed.

One method is to use the removecallbacks method. In this case, the thread is not executed, so run is not called.

5. Use the postdelayed method of handler to delay the thread to be added to the queue

Handler. postdelayed (updatethread, 3000)

The following is a simple code:

Package my. handler; import android. app. activity; import android. OS. bundle; import android. OS. handler; import android. view. view; import android. view. view. onclicklistener; import android. widget. button; public class handleruseactivity extends activity {/** called when the activity is first created. * // declare the two control variables private button startbutton = NULL; private button endbutton = NULL; @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); // obtain the control object startbutton = (button) findviewbyid (R. id. startbutton); endbutton = (button) findviewbyid (R. id. endbutton); // sets the listener startbutton. setonclicklistener (New startlistener (); endbutton. setonclicklistener (New endlistener ();} class startlistener implements onclicklistener {@ overridepublic void onclick (view V) {// todo auto-generated method stub // Add the thread updatethread to the thread queue handler. post (updatethread) ;}} class endlistener implements onclicklistener {@ overridepublic void onclick (view v) {// todo auto-generated method stub // remove the updatethread thread from the thread queue handler. removecallbacks (updatethread) ;}// apply for the handler Object Handler handler = new handler (); // create a thread, when a thread is called, it must call its run function/* runnable updatethread = new runnable () {public void run () {system. out. println ("updatethread"); // Add the thread updatedata to the thread queue handler after a delay of three seconds. postdelayed (updatethread, 3000) ;}}; * // inherits runnable or thread updatethread = new thread () {public void run () {system. out. println ("updatethread thread"); // Add the thread updatedata to the thread queue handler after a delay of three seconds. postdelayed (updatethread, 3000 );}};}
Package progressbar. handler; import android. app. activity; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. view. view; import android. view. view. onclicklistener; import android. widget. button; import android. widget. progressbar; public class progressbarhandleractivity extends activity {/** called when the activity is first created. */private button startbutton = nu Ll; private progressbar bar = NULL; int I = 0; @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); startbutton = (button) findviewbyid (R. id. startbutton); bar = (progressbar) findviewbyid (R. id. bar); startbutton. setonclicklistener (New startlistener ();} class startlistener implements onclicklistener {@ overridepublic void onclick (View V) {// todo auto-generated method stubbar. setvisibility (view. visible); handler. post (updatebar) ;}/// handler internally implements an anonymous internal class, heavy Load message processing function // call the handlemessage function when a message is taken out of the queue. The advantage of this function is that the arg1 parameter is more efficient. Handler handler = new handler () {public void handlemessage (Message MSG) {bar. setprogress (MSG. arg1); handler. post (updatebar) ;}}; thread updatebar = new thread () {public void run () {system. out. println ("begin thread! "); I = I + 1; message MSG = handler. obtainmessage (); MSG. arg1 = I; try {thread. sleep (1000);} catch (interruptedexception e) {e. printstacktrace ();} // sends a message and adds the message to the handler in the message queue. sendmessage (MSG); if (I = 100) {handler. removecallbacks (updatebar );}}};}

Note: The post method is used to put the thread object into the queue for execution. Instead of starting a new thread, the thread is directly called.

The run method of the object, so thread Asynchronization is not implemented.

The solution is to generate a handlerthread object and start it (START)

Use the getlogoff method of the handlerthread object to obtain its logoff object. Note that you must start before this, otherwise this

Logoff is empty

And pass the logoff object as a parameter to the handler object so that the handler object is bound to the thread where the logoff is located.

In this case, you need to override the handler class constructor and pass the logoff object to the parent class.

Logoff: class, which provides the function of cyclically obtaining messages from the queue. Do not create a message yourself.

In this way, the handler can repeatedly retrieve messages from the message queue.

The following code uses this method:

Package handler. extr; import android. app. activity; import android. OS. bundle; import android. OS. handler; import android. OS. handlerthread; import android. OS. logoff; import android. OS. message; public class handlerextractivity extends activity {/** called when the activity is first created. * // @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); // generate a handlerthread object, which implements the handlerthread = new handlerthread ("Handler-thread") function to use logoff to process message queues "); // start the thread handlerthread. start (); myhandler = new myhandler (handlerthread. getlooper (); message msg0 = myhandler. obtainmessage (); bundle B = new bundle (); B. putint ("Age", 25); B. putstring ("name", "xiaocheng"); msg0.setdata (B); msg0.arg1 = 0; // send the message to the target object, the target object is the handler object msg0.sendtotarget (); system. out. println ("activity --->" + thread. currentthread (). GETID ();} // to process a message, the handlemessage method must be inherited. // once inherited, you need to override the constructor to transmit the logoff parameter class myhandler extends handler {public myhandler () {} public myhandler (low.logoff) {super (logoff);} @ overridepublic void handlemessage (Message MSG) {// todo auto-generated method stubint age = MSG. getdata (). getint ("Age"); string name = MSG. getdata (). getstring ("name"); system. out. println ("handler --->" + thread. currentthread (). GETID (); system. out. println ("My name is" + name + ", and my age is" + age); system. out. println ("MSG ---- AGR1 is" + MSG. arg1); try {thread. sleep (1000);} catch (interruptedexception e) {e. printstacktrace ();} super. handlemessage (MSG );}}}
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.