Android: asynchronous Processing Using Handler

Source: Internet
Author: User

1. One problem

There is such a problem that deserves our consideration. If we write some functions similar to the download function that is time-consuming and does not necessarily have results) in the Activity (main thread), it will cause Activity blocking, no response for a long time until the page is suspended (if the page is not completed in five seconds, an error message "force close" will be received from the Android system "). Therefore, we need to put these time-consuming operations in separate child threads. This is the mission of Handler. Handler provides the asynchronous processing function. Sending and receiving are not the same (the main thread of the Activity and threads in the thread queue are different threads, which are executed in parallel without affecting each other ).

Ii. Handler Introduction

Handler is a thread communication tool in the Android operating system. It mainly plays two roles: (1) arranging a message or Runnable to execute somewhere in a main thread (2) schedule an action to be executed in another thread. Each Handler object maintains two queues (FIFO), message queue, and Runnable queue, which are provided by the Android operating system. Handler can use these two queues to separate:

Handler can be used in three steps: 1. Create a Handler object. 2. Create Runnable and message. 3. Call the post and sendMessage methods to add Runnable and message to the queue.

3. Runnable queue

1. threads in java

In java, there are two ways to create a Thread: Inherit the Thread class and implement the Runnable interface. The most important thing is to re-write the run method to implement the thread function. When the time slice of the thread arrives, the run () function is executed and the execution is complete, and the process enters the dead state.

Example of creating a thread:

 
 
  1. Runnable r=new Runnable(){ 
  2.  
  3. @Override 
  4. public void run() { 
  5. // TODO Auto-generated method stub 
  6. System.out.println("thread"); 
  7. handler.postDelayed(thread, 3000); 
  8. }; 

2. About Runnable queue

(1) Principle

Android thread asynchronous processing mechanism: the Handler object maintains a thread queue. When a new Runnable is sent to post (), it is placed at the end of the queue. When Runnable is processed, extract Runnable from the team header for execution. When a Runnable is sent to the queue, it returns immediately, regardless of whether the Runnable is executed or whether the execution is successful. The specific execution is performed by the system after the Runnable is queued. This is like an example of a post office. The sender writes the mail and puts it in the mail box to go home. He does not know when the mail is delivered by the post office, when it is sent, and how the recipient reads the mail. In this way, Android asynchronous processing is implemented.

(2) specific operations

Add thread to queue:

Handler. post (Runnable); add Runnable directly to the queue

Handler. postDelayed (Runnable, long) after a certain delay, add Runnable to the queue

Handler. postAtTime (Runnable, long) regularly adds Runnable to the queue

Termination thread:

Handler. removeCallbacks (thread); extract Runnable from Runnable queue

4. Message Queue

1. Message object

(1) Message object

The Message object carries data. Generally, it uses arg1 and arg2 to transmit messages. Of course, it can also have the obj parameter and can carryBundleData. It features a low consumption of system performance.

Initialization: Message msg = handler. obtainMessage ();

(2) Bundle object

Bundle is a class provided by Android. It can be considered as a special Map, that is, a key-Value Pair package. In particular, keys and values must be the basic data type or the key value of the basic data type array Map must be an object). In particular, keys must be of the String type. Use Message to carry Bundle data:

Put: msg. setData (Bundle bundle );

Retrieve: msg. getData ();

2. About message queues

(1) Principle

Android message asynchronous processing mechanism: the Handler object maintains a message queue. When a new message is sent to sendMessage (), it is placed at the end of the queue and then queued to process the message, handleMessage () is processed by the Handler object of the main thread ()). The entire process is asynchronous, which is the same as the Runnable queue.

(2) specific operations:

Add Runnable: handler. sendMessage (Message) to the queue );

Send the message to message queue msg. sendToTarget ();

After a delay of some time, send the Message to the Message Queue handler. sendMessageDelayed (Message, long );

Regularly send messages to the Message Queue handler. sendMessageAtTime (Message, long)

Message Processing:

The handleMessage (Message msg) method of Handler needs to be rewritten using the anonymous internal class when the new Handler object is used, as follows:

 
 
  1. Handler handler=new Handler(){ 
  2.  
  3. @Override 
  4. public void handleMessage(Message msg) { 
  5. // TODO Auto-generated method stub 
  6. 。。。。。。 
  7.  
  8. 。。。。。。 
  9. }; 
5. Two Functions of Handler

1. Schedule a message or Runnable to be executed somewhere in a main thread

Sample Code:

 
 
  1. public class HandlerTestActivity extends Activity { 
  2. private Button start; 
  3. @Override 
  4. protected void onCreate(Bundle savedInstanceState) { 
  5. // TODO Auto-generated method stub 
  6. super.onCreate(savedInstanceState); 
  7. setContentView(R.layout.handlertest); 
  8. start=(Button) findViewById(R.id.start); 
  9. start.setOnClickListener(new startListener()); 
  10.  
  11. System.out.println("Activity Thread:"+Thread.currentThread().getId()); 
  12. Handler handler=new Handler(); 
  13. Runnable thread=new Runnable(){ 
  14.  
  15. @Override 
  16. public void run() { 
  17. // TODO Auto-generated method stub 
  18. System.out.println("HandlerThread:"+Thread.currentThread().getId()); 
  19.  
  20. }; 
  21. class startListener implements OnClickListener{ 
  22.  
  23. @Override 
  24. public void onClick(View v) { 
  25. // TODO Auto-generated method stub 
  26. handler.post(thread); 
  27.  

In this small program, first start the program and enter onCreate), print the ID of the current thread (the main thread), and then click start to add the thread to the thread queue column, the thread is used to print the ID of the current thread. In this program, we can see that through Handler we can arrange Runnable to execute somewhere in a main thread, that is, role (1 ).

But there is a small trap. Have you found it? This program seems to have implemented the asynchronous mechanism of Handler, and handler. post (thread) seems to have implemented the role of a new startup thread. However, through execution, we find that the IDs of the two threads are the same! That is to say, in fact, the thread is still the original main thread. It can be seen that the handler. post () method does not actually create a new thread, but is only executed on the original thread. We have not implemented the asynchronous mechanism.

2. Schedule an action to be executed in another thread.

(1) java standard thread Creation Method

Step 1:

 
 
  1.  Runnable r=new Runnable(){ 
  2.  
  3. @Override 
  4. public void run() { 
  5. // TODO Auto-generated method stub 
  6. System.out.println("thread"); 
  7. handler.postDelayed(thread, 3000); 
  8. }; 

Step 2:

 
 
  1. Thread t=new Thread (r); 

Step 3:

 
 
  1. t.start(); 

If you change the handler. post (thread); statement in the preceding example program to the preceding format, we can see that the two IDs are different and the new thread starts!

(2) about Logoff

The logoff class is used to enable a message loop for a thread to read messages from the Message Queue cyclically. Therefore, logoff is actually the encapsulation of Message Queue + message loop. Each thread can correspond to only one logoff. Except for the main thread, the Android thread does not enable logoff by default.

Through Handler interaction with logoff, Handler can be seen as a logoff interface, used to send messages to a specified logoff and define the processing method. By default, Handler is bound to the Logoff of the thread where it is located, that is:

Handler handler = new Handler (); equivalent to Handler handler = new Handler (lofter. mylofter ());

Logoff has two main methods:

Lorule. prepare (); Enable lorule
Logoff. loop (); enables logoff to start working, fetch messages from the message queue, and process messages.

Note: Write it in logoff. the code after loop () will not be executed. This function should be a loop. When mHandler is called. getLooper (). after quit (), the loop will be aborted, and the subsequent code can be run.

(3) Implementation of Handler asynchronous mechanism

Handler uses HandlerThread to make the sub-thread and the main thread belong to different threads. In fact, HandlerThread is a special thread, which encapsulates logoff,

Sample Code:

 
 
  1. // Create a HandlerThread object named handler_hread
  2. HandlerThread handlerThread = new HandlerThread ("handler_hread ");
  3.  
  4. // Enable handlerThread. You must call the start method before using handlerThread. getLooper (); otherwise, the result is empty.
  5. HandlerThread. start ();
  6.  
  7. // Bind the handler to The logoff of the handlerThread, that is, the handler is running in the handlerThread.
  8. MyHandler handler = new myHandler (handlerThread. getLooper ());
  9.  
  10. Class myHandler extends Handler {
  11. Public myHandler (){}
  12. Public myHandler (low.logoff ){
  13. Super (logoff );
  14. }
  15. @ Override
  16. Public void handleMessage (Message msg ){
  17. // TODO Auto-generated method stub
  18. System. out. println ("Activity Thread:" + Thread. currentThread (). getId ());
  19. }
  20. }

In this way, the asynchronous Processing Mechanism of handler is implemented. by calling the handler. post () method, we can know that the subthread and the main thread belong to different threads by printing the thread ID.

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.