The third part of Android advanced-in-depth understanding of handler

Source: Internet
Author: User

Handler related instructions:
New Handler, it's bound to the thread/message queue of the thread that's creating it-- for

Similarly, there is a class:

Android.osclass Handlerthread
class  for new thread that has a looper. The looper can then is used to create handler classes. Note that start () must still is called.

Explanation: The UI thread of Android (that is, the thread created by the OnCreate function) is thread-insecure. That is, in the UI thread, using functions such as sleep causes the entire thread to delay, but in Android development, we often encounter some very slow operations, such as getting data information over HTTP, which can affect the rendering of the UI interface if it is placed in the main thread. However, if another thread is opened, the UI interface for the main thread cannot be modified because the UI thread can only be modified in the main thread. This time handler out to solve the problem.

Handler can distribute the Message object and the Runnable object into the main thread, each handler instance is bound to create his line approached (typically in the main thread), meaning that after the handler object is initialized, The default is bound to the message queue of the process it initializes, so you can take advantage of the message queues that handler contains to make some sequence of operations.

Handler mainly two major functions:

1. Provide post operation. The post operation primarily puts the Runnable object into the queue in the main thread (UI) threads. The Post also supports deferred operations. After using post, the runnable is executed on a per-queue basis.

2. Handlermessage operation. Primarily used to open a new thread to communicate with the main threads. After the new thread executes, it can send a message to the main thread via SendMessage and pass some parameters, then the main thread can modify the UI interface.

Functions provided by handler:

The Post class method allows you to arrange a runnable object into the main thread queue:

Post (Runnable)

Postattime (Runnable,long)

Postdelayed (Runnable Long)

The SendMessage class method allows you to schedule a message object with data in the queue:

Sendemptymessage (int)

SendMessage (Message)

Sendmessageattime (Message,long)

Sendmessagedelayed (Message,long)

Application Examples:

   1, passing message . Used to accept data sent by a child thread   and updated with this data with the main thread ui .

           in android, for ui operations usually need to be placed in the main thread. If there is an operation in the child thread about ui, then we need to use the data message as a handler The Handlermessge method processes the transmitted data information and operates ui. Class sendmessagehandler objects Handlemessage method to receive messgae and related operations.

2. Pass the Runnable object. Used for Message Queuing that is bound by Handler to schedule the execution of different operations.

When the handler object is initialized, the message queue is automatically bound by default. The class Post method enables you to send a Runnable object to a message queue and execute the Run method in the different Runnable objects sequentially, in the same way as the queue mechanism .

In addition,Android CPU allocation of the smallest unit is a thread,handler is generally created in a line thread, so handler and thread are bound to each other, one by one. While runnable is an interface,thread is a subclass of Runnable. So, they're both a process. XML file:

View Code

PackageCom.example.androidexpriment;importAndroid.app.activity;importAndroid.os.bundle;importAndroid.os.handler;importAndroid.util.log;importAndroid.view.view;importAndroid.view.view.onclicklistener;importAndroid.widget.button;public class Mainactivity extendsActivity {private String TAG = "Mainactivity"; Declaring two Button controls private button Startbutton = null; Private Button Endbutton = null; @Override public voidOnCreate (Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main); The object that represents the control is obtained based on the ID of the control, and the corresponding listener is set for both buttons Startbutton =(Button) Findviewbyid (R.id.startbutton); Startbutton.setonclicklistener (NewStartbuttonlistener ()); Endbutton =(Button) Findviewbyid (R.id.endbutton); Endbutton.setonclicklistener (new Endbuttonlistener ()); LOG.I (TAG, "activity-->" + Thread.CurrentThread (). GetId ());} class Startbuttonlistener implements  onclicklistener{@Override public void OnClick (View v) {//Call handler's Post method, and the thread object to be executed is added to the queue handler.post ( Updatethread); }} class Endbuttonlistener implements onclicklistener{@Override public void OnClick (View v) {Handler.removecall Backs (Updatethread); }}//Create a Handler object Handler Handler = new Handler ();//The operation to be performed write the run method of the thread object Runnable updatethread = new Runnable ( {@Override public void run () {log.i (TAG, "Updatethread"); LOG.I (TAG, "activity-->" + Thread.CurrentThread (). GetId ());//Within the Run method, execute the postdelayed or POST method Handler.postdelayed (Updatethread);}}; } 

When you click Start, the program runs every 3 seconds and prints a line of updatetread on the console . This is because the Updatethread object that implements the Runnable interface enters an empty message queue and is immediately executed by the run method, and within the run method, it is sent again into the message queue after 3000ms.

Note This method of creating handler objects does not require overriding the Handlermessage method.

It can be seen from the output results:

Although the Post method sends a class object that implements the Runnable interface, it does not create a new thread, but instead executes the Run method in the object . That is, the operations in the entire run are on the same thread as the main threads. This does not seem to affect those simple operations. But for long-time operations, there will be "suspended animation." To solve this problem, you need to bind the handler to a new open thread's message queue and process the runnable objects and messages that pass through the message queue on the other thread. The runnable object is passed only as an object that encapsulates the operation and does not produce a new thread.

The following is also possible:

PackageCom.example.androidexpriment;importAndroid.app.activity;importAndroid.os.bundle;importAndroid.os.handler;importAndroid.util.log;importAndroid.view.view;importAndroid.view.view.onclicklistener;importAndroid.widget.button;public class Mainactivity extendsActivity {Testthread T = null; Private String TAG = "Mainactivity"; Declaring two Button controls private button Startbutton = null; Private Button Endbutton = null; @Override public voidOnCreate (Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main); The object that represents the control is obtained based on the ID of the control, and the corresponding listener is set for both buttons Startbutton =(Button) Findviewbyid (R.id.startbutton); Startbutton.setonclicklistener (NewStartbuttonlistener ()); Endbutton = (Button) Findviewbyid (R.id.endbutton); Endbutton.setonclicklistener (new  Endbuttonlistener ()); LOG.I (TAG, "oncreate-->" +  Thread.CurrentThread (). GetId ()); t= new Testthread (1 );} class Startbuttonlistener implements  onclicklistener{@Override public void  OnClick (View v) {//Call handler's Post method, Add the thread object you want to execute to the queue  handler.post (t);}} Class Endbuttonlistener implements  onclicklistener{@Override public void  OnClick (View v) { Handler.removecallbacks (t); }}//Create a Handler object Handler Handler = new  Handler (); class Testthread extends  thread{int  Prime; Testthread (int  prime) {this.prime =  prime;} @Override public void  Run () {//within the Run method, execute postdelayed or P Ost method Handler.postdelayed (T, + ); LOG.I (TAG, "testthread-->" +  Thread.CurrentThread (). GetId ());}} }  

Although a thread was created, the start () method of the thread was not executed. Given the relationship between thread and runnable, there is no real difference between the two types of code, so there is not even a log in Logcat that starts a new thread.

However, if you modify it slightly: plus the Start method

  Class Startbuttonlistener implements onclicklistener{             @Override public          void OnClick (View v) {               // Call handler's Post method and add the thread object that will be executed to the queue              handler.post (t);             T.start ();         }                }             

It can be seen that although a new thread is started, the post can still push the thread into the main thread, and the thread is automatically ended by the virtual machine.

So, in the UI thread (main thread):

Mhandler=new Handler ();

Mhandler.post (New Runnable () {

void Run () {

Execute code :

}

});

This thread is actually running within the UI thread and does not have a new thread.

Common ways to create new threads are: Refer to the J2SE documentation

1.

Class Primethread extends Thread {         long minprime;         Primethread (Long minprime) {             this.minprime = minprime;         }         public void Run () {             //compute primes larger than minprime             ...         }  }

    • The following code would then create a thread and start it running:

           Primethread p = new Primethread (143);     P.start ();

2.

Class Primerun implements Runnable {         long minprime;         Primerun (Long minprime) {             this.minprime = minprime;         }         public void Run () {             //compute primes larger than minprime             ...         }     }
    • The following code would then create a thread and start it running:

           Primerun p = new Primerun (143);     New Thread (P). Start ();

Try to follow the two methods given above, do not be affected by the network simple from the Threa created, that can not be passed parameters.

static void sleep(long millis)Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, sub Ject to the precision and accuracy of system timers and schedulers.

Code Validation:

PackageCom.example.androidexpriment;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;public class Mainactivity extendsActivity {private String TAG = "Mainactivity"; Declaring two Button controls private button Startbutton = null; Private Button Endbutton = null; Testthread t = null; int flag = 0; @Override public voidOnCreate (Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main); The object that represents the control is obtained based on the ID of the control, and the corresponding listener is set for both buttons Startbutton =(Button) Findviewbyid (R.id.startbutton); Startbutton.setonclicklistener (NewStartbuttonlistener ()); Endbutton =(Button) Findviewbyid (R.id.endbutton); Endbutton.setonclicklistener (NewEndbuttonlistener ()); LOG.I (TAG, "oncreate-->" +Thread.CurrentThread (). GetId ()); t= New Testthread (1); } class Startbuttonlistener implementsonclicklistener{@Override public voidOnClick (View v) {//Call handler's Post method and add the thread object that will be executed to the queueT.start (); }} class Endbuttonlistener implementsonclicklistener{@Override public voidOnClick (View v) {handler.sendemptymessage (33); Flag = 5; }} class Testthread extendsthread{intPrime Testthread (intPrime) {This.prime =Prime } @Override public voidRun () {//Inside the Run method, execute postdelayed or Post method try {while (true ) {log.i (TAG, "testthread-->" +  Thread.CurrentThread (). GetId ()); Handler.sendemptymessagedelayed (22,3000); Thread.Sleep (), handler.sendemptymessage (+ ), if (flag = = 5)//Thread best exit method, is suicide, that is, the function of the threads of the natural return out return ;}} Catch  (Interruptedexception e) {//TODO auto-generated catch block  e.printstacktrace ();}}}//Create a Handler object Handler Handler = new  Handler () {@Override public void  handlemessage (Message msg) {//TODO auto-generated Me Thod stub Super . Handlemessage (msg); switch  (msg.what) {case : log.i (TAG, "Startbutton" ); LOG.I (Tag, "handler-->" +  Thread.CurrentThread (). GetId ()); break ; case: : LOG.I (Tag, "Endbutton" ); LOG.I (TAG, "handler-->" +  Thread.CurrentThread (). GetId ()); Break ;}}; }  

The third part of Android advanced-in-depth understanding of handler

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.