Handler Basic concepts: handler is mainly used for processing asynchronous messages: When a message is sent, first enters a message queue, the function that sends the message returns immediately, and the other part takes the message out of the message queue one by two, and then the message is is to send messages and receive messages that are not processed synchronously. This mechanism is often used to handle relatively long-time operations. Handler Common methods:
Post (Runnable)
Postattime (Runnable,long)
Postdelayed (Runnable Long)
Sendemptymessage (int)
SendMessage (Message)
Sendmessageattime (Message,long)
Sendmessagedelayed (Message,long)
The above Post class method allows you to arrange a runnable object into the main thread queue, SendMessage class method, which allows you to schedule a message object with data to queue and wait for updates.
Example Run logic:
Click button---> Start a new thread to process the data----> Data processing complete, return-----> Handler via handler to receive the returned data, UI update and so on.
Packagecom.example.handlertest;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.view.View;ImportAndroid.widget.TextView; Public classMainactivityextendsActivity {PrivateTextView text; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); Text=(TextView) Findviewbyid (R.id.textview); } //defines a handler that is used to process data asynchronouslyHandler Handler =NewHandler () { Public voidhandlemessage (android.os.Message msg) {System.out.println ("Results returned, processing ...."); if(Msg.what = = 1) {Text.settext ("Asynchronous processing result is = = = Handler"); } }; }; //a new thread is opened to process the data asynchronously, and the result is returned by handlerThread thread =NewThread () { Public voidrun () {System.out.println ("Start thread,,,,"); Handler.sendemptymessage (1); }; }; //Click the button Public voidStarttest (View v) {Thread.Start (); Try{Thread.Sleep (2000); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } System.out.println ("OnClick,,,,"); } }
Android------Handler processing messages asynchronously