Android: How does the main thread send messages to the subthread? android sends messages

Source: Internet
Author: User

Android: How does the main thread send messages to the subthread? android sends messages

Today, we will talk about how the main thread in Android sends messages to subthreads.
Perhaps it is nothing more than creating a Handler object, and then sending messages in one thread, and receiving messages in another ......
The principle is true, but we usually send messages to the main thread from the sub-thread, and the main thread has completed the logoff operation by default, therefore, we only need to simply "Create a Handler object, then one thread sends messages, and the other receives messages "......
Let's talk about this loose.
It is like a MessageQueue manager. A message queue has only one manager, and the manager processes the entire message queue, A Message Queue can contain multiple messages, while a worker (Handler) can also have multiple messages. The butler sends them to the Message Queue to store or retrieve the messages and execute the task;

Therefore, their numbers are as follows:
BUTLER: 1;
MessageQueue: 1;
Message: multiple messages are allowed;
Handler: Multiple workers are allowed;

The diagram is as follows:

After sorting out logoff Android source code, you can get the following content:

// ThreadLocal can be understood as a list of stored Loopers; ThreadLocal <lolocal> sThreadLocal = new ThreadLocal <loopiness> (); // loops' constructor private Loopers (boolean quitAllowed) {mQueue = new MessageQueue (quitAllowed); mThread = Thread. currentThread ();} 1. logoff. prepare () completes the following operations: sThreadLocal. set (new logoff (quitAllowed); 2. logoff. loop () completes the following operations: Looper me = sThreadLocal. get (); MessageQueue queue = me. mQueue ;...... // Continuously distribute messages cyclically for (;) {Message msg = queue. next ();...... Msg.tar get. dispatchMessage (msg); // The dispatchMessage (msg) method executes the following content: handler. handleMessage (msg); // handler executes the code in handleMessage (msg ;......};

Below is a small example:
When a Button is pressed, a number is sent from the main thread to the subthread, And the subthread displays the number with Toast, and the main thread sets TextView to the number;

Run the following command:

The following code is attached:

MainActivity. java:

Package activity.wyc.com. looperthreaddemo; import android. OS. handler; import android. OS. logoff; import android. OS. message; import android. support. v7.app. actionBarActivity; import android. OS. bundle; import android. util. log; import android. view. menu; import android. view. menuItem; import android. view. view; import android. widget. button; import android. widget. textView; import android. widget. toast; public class MainActivity extends ActionBarActivity {private String MyTag = "MyTag"; private int num = 0; private TextView tvObj; private Button btnObj; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); tvObj = (TextView) findViewById (R. id. tvid); btnObj = (Button) findViewById (R. id. btnid); final LooperThread looperThread = new LooperThread (); looperThread. start (); btnObj. setOnClickListener (new View. onClickListener () {@ Override public void onClick (View v) {Message message = Message. obtain (); message. arg1 = num; tvObj. setText ("sent by the main thread:" + String. valueOf (message. arg1); looperThread. handler. sendMessage (message); num ++;}) ;}class LooperThread extends Thread {public Handler handler; @ Override public void run () {super. run (); logoff. prepare (); handler = new Handler () {@ Override public void handleMessage (Message msg) {super. handleMessage (msg); Toast. makeText (MainActivity. this, "LooperThread handler receives the message:" + msg. arg1, Toast. LENGTH_LONG ). show (); Log. I (MyTag, "LooperThread handler receives the message:" + msg. arg1) ;}}; Looper. loop (); // loop () will call the handleMessage (Message msg) method of handler, so write it below ;}}}

Activity_main.xml:

<LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android" xmlns: tools = "http://schemas.android.com/tools" android: layout_width = "match_parent" android: layout_height = "match_parent" android: paddingLeft = "@ dimen/plugin" android: paddingRight = "@ dimen/plugin" android: paddingTop = "@ dimen/activity_vertical_margin" android: paddingBottom = "@ dimen/plugin" android: gravity = "center" android: orientation = "vertical" tools: context = ". mainActivity "> <TextView android: textSize =" 30sp "android: layout_width =" wrap_content "android: layout_height =" wrap_content "android: id = "@ + id/tvid"/> <Button android: layout_width = "match_parent" android: layout_height = "wrap_content" android: text = "the main thread sends a message to the subthread" android: textSize = "25sp" android: id = "@ + id/btnid"/> </LinearLayout>

The link to the source code is attached (Baidu cloud disk, I use Android studio to write code ):

Http://pan.baidu.com/s/1dDH84r3

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.