Android: How the main thread sends messages to child threads

Source: Internet
Author: User

Today, let's talk about how the main thread in Android sends a message to a child thread.
Perhaps the recollection is simply to create a handler object, then one thread sends the message, the other receives the message ...
The principle is really this, but we usually, is from the child thread to the main thread of the message, and the main thread by default has helped us to complete the operation of Looper, so we just need to simply "create a handler object, then one thread to send messages, another to receive the message" ...
Let's talk about this looper is God horse.
It is like a Message Queuing (MessageQueue) housekeeper (Looper), a message queue with only one housekeeper, and the manager of the entire message queue, while a message queue can hold multiple messages (message), while workers (Handler) can have more than one, The housekeeper dispatches them to perform tasks after storing or removing messages from the message queue;

So the number of them is as follows:
Housekeeper (Looper): one;
Message Queuing (MessageQueue): one;
Message: can be multiple;
Worker (Handler): can be multiple;

To Looper's Android source to organize a bit, you can get the following content:

//threadlocal can be understood as a list of storage looper;Threadlocal<looper> sthreadlocal =NewThreadlocal<looper> ();//looper's constructorPrivateLooper (Boolean quitallowed) {mqueue =NewMessageQueue (quitallowed);    Mthread = Thread.CurrentThread (); }1.LOoper.prepare () completed the following operation: Sthreadlocal.Set(NewLooper (quitallowed));2.LOoper.loop () completed the following operation: Looper me = Sthreadlocal.get (); MessageQueueQueue= Me.mqueue;//continuously circulate messages for(;;) {Message msg =Queue. Next (); ... msg.target.dispatchMessage (msg);The //dispatchmessage (msg) method performs the following:Handler.handlemessage (msg);//handler executes the code in Handlemessage (msg);......};

Here is a small example:
When a button is pressed, a number is sent from the mainline Cheng thread, and then the child thread displays the number with a toast, and the main thread is set TextView to that number;

Run as follows:

The following code is attached:

Mainactivity.java:

 PackageActivity.wyc.com.looperthreaddemo;ImportAndroid.os.Handler;ImportAndroid.os.Looper;ImportAndroid.os.Message;Importandroid.support.v7.app.ActionBarActivity;ImportAndroid.os.Bundle;ImportAndroid.util.Log;ImportAndroid.view.Menu;ImportAndroid.view.MenuItem;ImportAndroid.view.View;ImportAndroid.widget.Button;ImportAndroid.widget.TextView;ImportAndroid.widget.Toast; Public  class mainactivity extends actionbaractivity {    PrivateString MyTag ="MyTag";Private intnum =0;PrivateTextView Tvobj;PrivateButton 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);FinalLooperthread Looperthread =NewLooperthread ();        Looperthread.start (); Btnobj.setonclicklistener (NewView.onclicklistener () {@Override             Public void OnClick(View v)                {Message message = Message.obtain ();                MESSAGE.ARG1 = num; Tvobj.settext ("The main thread sent:"+string.valueof (MESSAGE.ARG1));                LooperThread.handler.sendMessage (message);            num++;    }        }); } class Looperthread extends Thread { PublicHandler Handler;@Override         Public void Run() {Super. Run ();            Looper.prepare (); Handler =NewHandler () {@Override                 Public void Handlemessage(Message msg) {Super. Handlemessage (msg); Toast.maketext (mainactivity. This,"Looperthread Handler received the message:"+msg.arg1,toast.length_long). Show (); LOG.I (MyTag,"Looperthread Handler received the message:"+ MSG.ARG1);            }            }; Looper.loop ();//loop () will call the Handlemessage (Message msg) method to handler, so write it down 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/activity_horizontal_margin"    Android:paddingright="@dimen/activity_horizontal_margin"    Android:paddingtop="@dimen/activity_vertical_margin"    Android:paddingbottom="@dimen/activity_vertical_margin"    android:gravity="Center"    android:orientation="Vertical"    Tools:context=". Mainactivity ">    <TextViewandroid:textsize="30sp"android:layout_width="Wrap_ Content "android:layout_height="wrap_content "android:id=" @+id/tvid " />                                    <buttonandroid:layout_width="Match_parent"android:layout_height= "Wrap_content" Android:text="Mainline Cheng thread sends message"android:textsize="25sp"android:id= "@+id/btnid" />                                        </linearlayout>

Finally attach the source of the link (Baidu cloud disk, I use Android Studio to write code):

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

Android: How the main thread sends messages to child threads

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.