Android: Handler

Source: Internet
Author: User

I. Handler Introduction

There is a message queue in a thread. When there is a message in the message queue, handler will process the messages. Let's consider this scenario:

It takes a long time for us to execute a business. After execution, we need to return a result displayed on textview. Is it reasonable for us to execute this business in the main thread?

Obviously it is unreasonable, so we will think of putting the business into sub-threads for execution, but android has a rule that all UI update operations must be completed in the main thread, so what we need to do is to upload the result of the sub-thread execution to the main thread and display it. This requires handler's help;

For example, handler is used for progressbar and textview;


If the application does not respond to user input within 5 seconds, the following error is thrown:



The handler principle is as follows:


Template code:

Package Org. xiazdong. handler; public class sampleactivity extends activity {private button; private handler = new handler () {@ overridepublic void handlemessage (Message MSG) {If (MSG. what = 1) {// update UI} If (MSG. what = 2) {// update UI }}; private onclicklistener listener = new onclicklistener () {class servicethread extends thread {private servicelistener = new servicelistener () {@ overridepublic void onservice (INT current) {// service listener // executes the message while sending it to the main thread handler. sendmessage (MSG) ;};@overridepublic void run () {// execute the business }}@ overridepublic void onclick (view v) {servicethread thread = new servicethread (); // The Sub-thread executes the business thread. start () ;};@ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); button = (button) This. findviewbyid (R. id. button); button. setonclicklistener (listener );}}

Ii. Instances


Program description:

Execute a business: from scratch, add 1 every 3 seconds until 5, return result 5, and display the number added in real time through progressbar;

Program class declaration:

(1) servicelistener interface: this interface is used to listen to services and perform execution logic based on services.

-Onservice (INT current );

(2) Service: this class is a service class that executes this business;

Execution result: Click start execution. The progress bar is added to 1 every three seconds. When the progress is full, result = 5 is displayed;



Servicelistener. Java

Package org. xiazdong. Handler;/*** service listener * @ author xiazdong **/public interface servicelistener {public void onservice (INT current );}

Service. Java

package org.xiazdong.handler;public class Service {private int sum = 5;private int current = 0;public void sum(ServiceListener listener)throws Exception{while(current<sum){Thread.sleep(3000);current++;listener.onService(current);}}}

Mainactivity. Java

Package Org. xiazdong. 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; import android. widget. textview; public class mainactivity extends activity {private textview; private button; private progressbar; private handler = new handler () {@ overridepublic void handlemessage (Message MSG) {If (MSG. what = 1) {int current = MSG. getdata (). getint ("current"); progressbar. setprogress (current);} If (MSG. what = 2) {int result = MSG. getdata (). getint ("result"); textview. settext ("result =" + result) ;}}; private onclicklistener listener = new onclicklistener () {class servicethread extends thread {private servicelistener = new servicelistener () {@ overridepublic void onservice (INT current) {// service listener message MSG = new message (); MSG. what = 1; MSG. getdata (). putint ("current", current); handler. sendmessage (MSG) ;};@overridepublic void run () {service = new service (); progressbar. setmax (5); // set the maximum progress progressbar. setprogress (0); // The initial progress is 0try {service. sum (servicelistener); // execute the service and input the listener to listen to the execution of the service. // when the execution is complete, send the final result 5 to textviewmessage MSG = new message (); MSG. what = 2; MSG. getdata (). putint ("result", 5); handler. sendmessage (MSG);} catch (exception e) {e. printstacktrace () ;}}@ overridepublic void onclick (view v) {servicethread thread = new servicethread (); // The Sub-thread executes the business thread. start () ;};@ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); textview = (textview) This. findviewbyid (R. id. textview); button = (button) This. findviewbyid (R. id. button); progressbar = (progressbar) This. findviewbyid (R. id. progressbar); button. setonclicklistener (listener );}}

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.