Android-- multithread of Looper

Recommended for you: Get network issues from WhatsUp Gold. Not end users.


  A blog on the Handler to realize the communication between threads, this blog on the principle of Handler operation, which involves MessageQueue, Looper. Briefly speaking, Handler will make a thread message is sent to the current thread's message queue, will process the message queue of messages from the message queue Handler, here is MessageQueue, and the management of message queue, is Looper.

  Handler, MessageQueue, The relationship between Looper among the three figure:

  You can see from the picture above, Handler sends the message to the current thread thread in MessageQueue, and Looper for the management of MessageQueue, from MessageQueue to Handler access to the message processing.


  Looper, Usually run on a circular queue a message, thread by default, do not give us a message loop to control the message queue. If you want to manage the message queue, need to call in the thread Looper.prepare () method to make the message loop initialization, and call Looper.loop () so that the message loop has been running, until the cessation of circulation. So Looper is mainly completed the MessageQueue interacts with Handler function.

  UI main thread in Activity, without the use of explicit Looper initialization mode and start the cycle, because the Activity contains a Looper object, it will automatically manage Looper, sent messages in the treatment of Zi Xiancheng. When the initialization of Handler, in the constructor of the Handler, the correlation of Looper and Handler for the current thread, so in Activity, without the need to explicitly use the Looper. Below by an example about Activity, examples of worker threads to the main thread to send the message.

  Realization of the code:

 1 package com.example.handlerlooperdemo;
 3 import;
 4 import android.os.Bundle;
 5 import android.os.Handler;
 6 import android.os.Looper;
 7 import android.os.Message;
 8 import android.view.View;
 9 import android.widget.Button;
10 import android.widget.TextView;
12 public class MainThreadActivity extends Activity {
13     private Button btnSendToUI1, btnSendToUI2;
14     private TextView tvSendMes1;
15     private static MyHandler handler;
17     @Override
18     protected void onCreate(Bundle savedInstanceState) {
19         super.onCreate(savedInstanceState);
20         setContentView(R.layout.looper_activity);
21         tvSendMes1 = (TextView) findViewById(;
22         btnSendToUI1 = (Button) findViewById(;
23         btnSendToUI2 = (Button) findViewById(;
25         btnSendToUI1.setOnClickListener(new View.OnClickListener() {
26             @Override
27             public void onClick(View v) {
28                 // Using the internal Activity Looper objects
29                 handler=new MyHandler();
30                 Message msg=Message.obtain();
31                 msg.what=1;
32                 msg.obj="The default Looper";
33                 handler.sendMessage(msg);
34             }
35         });
36         btnSendToUI2.setOnClickListener(new View.OnClickListener() {
37             @Override
38             public void onClick(View v) {
39                 // Gets the Looper of the current thread
40                 Looper looper=Looper.myLooper();
41                 handler=new MyHandler(looper);
43                 Message msg=Message.obtain();
44                 msg.what=2;
45                 msg.obj="Using the Looper of the current thread";
46                 handler.sendMessage(msg);
47             }
48         });
49     }
51     public class MyHandler extends Handler {
53         public MyHandler() {
54         }
56         public MyHandler(Looper looper) {
57             super(looper);
58         }
60         @Override
61         public void handleMessage(Message msg) {
62             super.handleMessage(msg);
63             tvSendMes1.setText("what=" + msg.what + "," + msg.obj);
64         }
65     }
66 }

  Implementation effect:

  Through the above Demo can see, although Handler has two constructors, one needs to pass a Looper object, one need not, but for the UI thread, which in fact is the same, because Activity will help us to maintain the Looper object.

  But the thread, without any objects help us to maintain the Looper object, so we need to own manual maintenance. It requires the use of prepare () and loop () method. The following implementation to demonstrate to Zi Xiancheng sent messages in the UI thread through a Demo. Note that, because the Handler is declared in the realization of Zi Xiancheng, so processing messages in Handler, must also comply with the thread limit, some can not be in the child thread to do things, can not achieve here, such as access network, UI component.

  Realization of the code:

 1 package com.example.handlerlooperdemo;
 3 import;
 4 import android.os.Bundle;
 5 import android.os.Handler;
 6 import android.os.Looper;
 7 import android.os.Message;
 8 import android.util.Log;
 9 import android.view.View;
10 import android.widget.Button;
11 import android.widget.Toast;
13 public class WorkThreadActivity extends Activity {
14     private Button btnSendToWorkUI;
15     private Handler handler;
16     @Override
17     protected void onCreate(Bundle savedInstanceState) {
18         super.onCreate(savedInstanceState);
19         setContentView(R.layout.looper_activity2);
21         // Open a sub thread in the UI thread
22         new Thread(new Runnable() {            
23             @Override
24             public void run() {
25                 // In the child thread initialization in a Looper object
26                 Looper.prepare();
27                 handler=new Handler(){
28                     @Override
29                     public void handleMessage(Message msg) {
30                         super.handleMessage(msg);
31                         // The UI thread to send the message on the screen. 
32                         Log.i("main", "what="+msg.what+","+msg.obj);
33                         Toast.makeText(WorkThreadActivity.this, "what="+msg.what+","+msg.obj, Toast.LENGTH_SHORT).show();
34                     }
35                 };    
36                 // The Looper object running just initialization, message queuing message loop
37                 Looper.loop();
38             }
39         }).start();
41         btnSendToWorkUI=(Button)findViewById(;
43         btnSendToWorkUI.setOnClickListener(new View.OnClickListener() {            
44             @Override
45             public void onClick(View v) {
46                 // The onClick method is running on the UI thread 
47                 Message msg=Message.obtain();
48                 msg.what=1;
49                 msg.obj="To send the child thread message!";
50                 // To send the child thread message
51                 handler.sendMessage(msg);
52             }
53         });
54     }
57 }

  Results show:

  Download the source code


  This blog to explain the principles of Handler in transmitting messages, and also illustrate how the UI thread and Zi Xiancheng mutual communication, although in the actual development process, realize the rarely used UI thread to thread to send the message, but through this example is a better description of the principles of Looper.

  Please support the original, respect the original, reproduced please indicate the source. Thank you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Abelard at November 20, 2013 - 5:53 PM