Android handler, thread implements asynchronous tasks

Source: Internet
Author: User

"Turn" http://blog.csdn.net/lanpy88/article/details/6659630

The definition of a 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. At this time, handler appeared to solve this complex problem, because handler runs 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 to pass over ( The child thread uses the Sedmessage () method to transmit the message object, which contains data, which is placed in the main thread queue and updated with the main thread.

Two use process:

1 defining the Handler object and initializing it, overriding the Handlemessage () function

2 defines the thread threading object, usually written as a class form (such as Class ThreadTest implements Runnable), manipulating the data in the run () method, and transferring the data Handler.sendmessage () method Into the handler object, and the thread is turned on. (Note: This step does not have to be done with thread, or it can be implemented with Timetask, and the operation is also placed in the run () method)

3 different methods are implemented in the Handlemessage () function according to different data forms.

Instance:

Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.os.Message;ImportAndroid.util.Log;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button;ImportAndroid.widget.TextView; Public classMainacitivityextendsActivity {/**Called when the activity is first created.*/    PrivateHandler handler=NewHandler () { Public voidhandlemessage (Message msg) {Switch(MSG.ARG1) { Case1: Txttextview.settext ("BBBB");  Break;  Case2: Settitle ("AAA"); default:                 Break;    }        }    }; PrivateButton btn; PrivateTextView Txttextview; @Override Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.main); Txttextview=(TextView) Findviewbyid (R.id.txtview); BTN=(Button) Findviewbyid (R.ID.BTN); Btn.setonclicklistener (NewOnclicklistener () { Public voidOnClick (View arg0) {threadtest threadtest=Newthreadtest (); NewThread (threadtest). Start (); ThreadTest2 ThreadTest2=NewThreadTest2 (); NewThread (ThreadTest2). Start ();    }        }); }    Private classThreadTestImplementsrunnable{ Public voidrun () {//TODO auto-generated Method Stub            Try{Thread.Sleep (1000); }            Catch(Exception e) {e.printstacktrace (); } Message msgmessage=NewMessage (); Msgmessage.arg1=1;            Handler.sendmessage (Msgmessage); LOG.E ("ThreadName", Thread.CurrentThread (). GetName ()); }            }        Private classThreadTest2Implementsrunnable{ Public voidrun () {//TODO auto-generated Method Stub            Try{Thread.Sleep (1000); }            Catch(Exception e) {e.printstacktrace (); } Message msgmessage=NewMessage (); Msgmessage.arg1=2;            Handler.sendmessage (Msgmessage); LOG.E ("ThreadName", Thread.CurrentThread (). GetName ()); }            }}

Simple version: Define a button, click the button asynchronous implementation, replace the button's text

 Packagecom.example.handlertest;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.os.Message;Importandroid.app.Activity;ImportAndroid.view.Menu;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button; Public classMainactivityextendsActivity {PrivateButton start; //define handler to perform different UI update operations based on receiving different messages    PrivateHandler Handler =NewHandler () { Public voidhandlemessage (android.os.Message msg) {//put the code to update the UI thread here           Switch(MSG.ARG1) { Case0: Start.settext ("Merry Christmas:)");  Break; default:             Break;    }       };        }; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Start=(Button) Findviewbyid (R.id.start); Start.setonclicklistener (NewHandleonclicklistener ()); }         Private classHandleonclicklistenerImplementsview.onclicklistener{@Override Public voidOnClick (View arg0) {//TODO auto-generated Method Stub//to open a new threadThreadTest threadtest =Newthreadtest ();                    Threadtest.start ();        }    }; Private classThreadTestextendsThread { Public voidrun () {Try{Thread.Sleep (3000); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }            //take time-consuming actions to send handler messagesMessage Msgtosend =NewMessage (); Msgtosend.arg1= 0;        Handler.sendmessage (Msgtosend);        }    }; @Override Public BooleanOncreateoptionsmenu (Menu menu) {//inflate the menu; This adds items to the action bar if it is present.getmenuinflater (). Inflate (R.menu.main, menu); return true; }}

Android handler, thread implements asynchronous tasks

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.