Android main thread and child threads send messages to each other, and send messages to themselves

A little trick to use handler
Use RUnable interface, and then use postDeleyed();
the principle is to use the ThreadRunable interface to achieve




Development  steps:
1. Create a new Android application 
2. Add 2 Button control labels to the layout file and set them Attributes and values 
​​3. In the Activity, declare the control variable and obtain the control object according to the id 
4. In the Activity, create a Handler object 
5. In the Activity, create a Runnable object 
a) In the way of anonymous inner class 
b) Will be executed The operation is written in the run() method in the Runnable object 
i. Print out a sentence 
ii. Call the postDelayed() method of the Runnable object 
6. In the Activity, write the listener required for the start button and bind 
a) in this In the Onclick() method of the listener, the post() method of the Handler is called, and the thread object to be executed is placed in the queue. 
7. In the Activity, write the listener required by the end button, and help determine 
a) In the Onclick() method of this listener, call the removeCallbacks() method of the Handler to delete the thread objects that are not executed in the queue. 
b)
Below is the code of the Activity: 
Java code  
package android.handler;  
  
import android.app.Activity;  
import android.os.Bundle;  
import android.os.Handler;  
import android.view.View;  
import android.view.View.OnClickListener;  
import android.widget.Button;  
  
public class HandlerTest extends Activity {  
      
    private Button startButton;  
    private Button endButton;  
      
    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  
        //根据id获得控件对象  
        startButton = (Button)findViewById(R.id.startButton);  
        endButton = (Button)findViewById(R.id.endButton);  
        //Set the listener for the control  
        startButton.setOnClickListener(new StartButtonListener());  
        endButton.setOnClickListener(new EndButtonListener());  
    }  
      
    class StartButtonListener implements OnClickListener{  
        public void onClick (View v) {  
            //Call the post() method of Handler and put the thread object to be executed in the queue  
            handler.post(updateThread);  
        }  
    }  
      
    class EndButtonListener implements OnClickListener{  
        public void onClick(View v) {  
            //Call Handler The removeCallbacks() method removes unexecuted thread objects from the queue  
            handler.removeCallbacks(updateThread);  
        }  
          
    }  
      
    //Create a Handler object  
    Handler handler = new Handler();  
    //Create a new thread object  
    Runnable updateThread = new Runnable(){  
        //Write the operation to be performed in the run method of the thread object  
        public void run(){  
            System.out.println("updateThread");  
            //Call the postDelayed() method of Handler  
            //The function of this method is to put the thread object to be executed into the queue, and after the time is up, Run the specified thread object  
            // The first parameter is the Runnable type: the thread object to be executed  
            // The second parameter is the long type: the delay time, in milliseconds  
            handler.postDelayed(updateThread, 3000);  
        }  
    };  
}  


The above is the simplest example, let's look at another example below. 


The above is transferred from low-level writers




===========================


1. Several key concepts 
1. MessageQueue: It is a data structure, see the name , is a message queue, where messages are stored. Each thread can have at most one MessageQueue data structure. 
When a thread is created, its MessageQueue is not automatically created. Usually a Looper object is used to manage the thread's MessageQueue. When the main thread is created, 
a , and the creation of the Looper object will automatically create a Message Queue. Other non-main threads do not automatically create Looper, and when needed, 
call  prepare function to achieve it.
2. Message: message object, the object stored in the Message Queue. A Message Queue contains multiple Messages. 
To obtain the Message instance object, the static method obtain() in the Message class is usually used. This method has multiple overloaded versions to choose from; its creation does not necessarily directly create a new instance, 
but starts from the Message Pool (message pool) to see if there is an available Message instance, if it exists, take it out and return it directly. If no Message instance is available in the Message Pool, 
a Message object is created with the given parameters. When calling removeMessages(), the Message is removed from the Message Queue and placed in the Message Pool at the same time. Except for the above 
In this way, you can also obtain a Message instance through the obtainMessage() of the Handler object. 
3. Looper: 
is the manager of MessageQueue. Each MessageQueue cannot exist without Looper, and the creation of Looper objects is achieved through the prepare function. At the same time, each Looper object is 
associated with a thread. By calling Looper.myLooper(), the Looper object of the current thread can be obtained. 
When a Looper object is created, a MessageQueue object will be created at the same time. In addition to the default Looper for the main thread, other threads do not have MessageQueue objects by default, so 
Messages cannot be accepted. If you need to accept it, define a Looper object yourself (through the prepare function), so that the thread has its own Looper object and MessageQueue data structure. 
The Looper takes out the Message from the MessageQueue and then hands it over to the Handler's handleMessage for processing. After processing, call Message.recycle() to put it into the Message Pool. 
4. Handler: 
The handler of the message. The handler is responsible for encapsulating the information to be delivered into a Message, which is achieved by calling the obtainMessage() of the handler object; 
the message is passed to the Looper, which is achieved through the sendMessage() of the handler object. Then Looper puts the Message into the MessageQueue. 
When the Looper object sees a Message in the MessageQueue, it broadcasts it. After the handler object receives the message, it calls the handleMessage() method of the corresponding handler object 
to process it. 
2. How to transfer messages between threads 
1. The main thread sends itself a Message 
package test.message; 
import android.app.Activity; 
import android.os.Bundle; 
import android.os.Handler; 
import android.os.Looper ; 
import android.os.Message; 
import android.view.View; 
import android.widget.Button; 
import android.widget.TextView; 
public class MainActivity extends Activity { 
    private Button btnTest; 
    private TextView textView; 
    private Handler handler; 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main); 
        btnTest = (Button)this.findViewById(R.id.btn_01); 
        textView = (TextView)this.findViewById(R .id.view_01); 
        btnTest.setOnClickListener(new View.OnClickListener() { 
            @Override 
            public void onClick(View arg0) { 
                Looper looper = Looper.getMainLooper(); //The Looper object 
                of the main thread //Here is the main thread's Looper object The Looper object creates a handler, 
                //So, the Message sent by this handler will be passed to the MessageQueue of the main thread. 
                handler = new MyHandler(looper); 
                handler.removeMessages(0); 
                //Build a Message object 
                //The first parameter: it is the message code specified by yourself, which is convenient for selectively receiving in the handler 
                //The second and third parameters are meaningless 
                //The fourth parameter is required Encapsulated object 
                Message msg = handler.obtainMessage(1,1,1,"The main thread sent a message"); 
                handler.sendMessage(msg); //Send message 
            } 
        }); 
    } 
    class MyHandler extends Handler{ 
        public MyHandler(Looper looper){ 
            super(looper); 
        } 
        public void handleMessage(Message msg){ 
            super.handleMessage(msg); 
            textView.setText("I am the Handler of the main thread and received a message: "+(String)msg.obj); 
        } 
    } 

2. Other threads send Message to the main thread 
package test.message; 
import android.app.Activity; 
import android.os.Bundle; 
import android.os.Handler; 
import android.os.Looper; 
import android.os.Message; 
import android.view.View; 
import android.widget.Button; 
import android.widget.TextView; 
public class MainActivity extends Activity { 
    private Button btnTest; 
    private TextView textView; 
    private Handler handler; 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main); 
        btnTest = (Button)this.findViewById(R.id.btn_01); 
        textView = (TextView)this.findViewById(R .id.view_01); 
        btnTest.setOnClickListener(new View.OnClickListener() { 
            @Override 
            public void onClick(View arg0) { 
                //It can be seen that a thread is started to operate the encapsulation and sending of messages 
                //So it turns out The sending of the main thread becomes the sending of other threads, is it simple? Ha ha 
                new MyThread().start();     
            } 
        }); 
    } 
    class MyHandler extends Handler{ 
        public MyHandler(Looper looper){ 
            super(looper); 
        } 
        public void handleMessage(Message msg){ 
            super.handleMessage(msg); 
            textView.setText("I am the Handler of the main thread and received a message: "+(String)msg .obj); 
        } 
    } 
    //Added a thread class 
    class MyThread extends Thread{ 
        public void run(){ 
            Looper looper = Looper.getMainLooper(); //The Looper object 
            of the main thread //This is created with the Looper object of the main thread The handler, 
            //So, the Message sent by this handler will be passed to the MessageQueue of the main thread. 
            handler = new MyHandler(looper); 
            //build the Message object 
            //The first parameter: It is the message code specified by yourself, which is convenient for selectively receiving in the handler 
            //The second and third parameters are meaningless 
            //The fourth parameter needs to be encapsulated by the object 
            Message msg = handler.obtainMessage(1, 1,1,"Other thread sent a message"); 
            handler.sendMessage(msg); //Send message             
        } 
    } 

3. The main thread sends Message to other threads 
package test.message; 
import android.app.Activity; 
import android .os.Bundle; 
import android.os.Handler; 
import android.os.Looper; 
import android.os.Message; 
import android.view.View; 
import android.widget.Button; 
import android.widget.TextView; 
public class MainActivity extends Activity { 
    private Button btnTest; 
    private TextView textView; 
    private Handler handler; 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main); 
        btnTest = (Button)this.findViewById(R.id.btn_01); 
        textView = (TextView)this.findViewById(R.id.view_01); 
        //启动线程 
        new MyThread().start();     
        btnTest.setOnClickListener(new View.OnClickListener() { 
            @Override 
            public void onClick(View arg0) { 
                //The handler is instantiated in the thread. 
                //Message is instantiated when the thread starts. 
                msg = handler.obtainMessage(1,1,1,"message sent by the main thread"); 
                handler.sendMessage(msg); 
            } 
        }); 
    } 
    class MyHandler extends Handler{ 
        public MyHandler(Looper looper){ 
            super(looper); 
        } 
        public void handleMessage(Message msg){ 
            super.handleMessage(msg); 
            textView.setText("I am the Handler of the main thread, Received the message: "+(String)msg.obj); 
        } 
    } 
    class MyThread extends Thread{ 
        public void run(){ 
            Looper.prepare(); //Create the Looper object of the thread to receive messages 
            //Note: the handler here is defined in the main thread, oh, huh, 
            //I saw that the handler object was used directly, yes Not looking, where is it instantiated? 
            // see now? ? ? Oh, it can't be instantiated at the beginning, because the Looper object 
            // of the thread doesn't exist yet. Now it can be instantiated 
            //Here Looper.myLooper() gets the Looper object of the thread 
            handler = new ThreadHandler(Looper.myLooper()); 
            //This method, any doubts? 
            //In fact, it is a loop, which takes messages from MessageQueue in a loop. 
            // Don't visit often, how do you know you have new news? ?
            Looper.loop();  
        } 
        //Define the message processing class in the thread class 
        class ThreadHandler extends Handler{ 
            public ThreadHandler(Looper looper){ 
                super(looper); 
            } 
            public void handleMessage(Message msg){ 
                //Here the Message in the MessageQueue in the thread is processed 
                //Here we return to the main thread a message 
                handler = new MyHandler(Looper.getMainLooper()) ; 
                Message msg2 = handler.obtainMessage(1,1,1,"Sub-thread received:"+(String)msg.obj); 
                handler.sendMessage(msg2); 
            } 
        } 
    } 

4. Other threads send Message  
package to themselves test.message; 
import android.app.Activity; 
import android.os.Bundle; 
import android.os.Handler; 
import android.os.Looper; 
import android.os.Message; 
import android.view.View; 
import android.widget.Button; 
import android.widget.TextView; 
public class MainActivity extends Activity { 
    private Button btnTest; 
    private TextView textView; 
    private Handler handler; 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main); 
        btnTest = (Button)this.findViewById(R.id.btn_01); 
        textView = (TextView)this.findViewById(R.id.view_01); 
        btnTest.setOnClickListener(new View.OnClickListener() { 
            @Override 
            public void onClick(View arg0) { 
                //启动线程 
                new MyThread().start();     
            } 
        }); 
    } 
    class MyHandler extends Handler{ 
        public MyHandler(Looper looper){ 
            super(looper); 
        } 
        public void handleMessage(Message msg){ 
            super.handleMessage(msg); 
            textView.setText((String)msg.obj); 
        } 
    }     
    class MyThread extends Thread{ 
        public void run(){ 
            Looper.prepare(); //创建该线程的Looper对象 
            //Here Looper.myLooper() gets the Looper object of the thread 
            handler = new ThreadHandler(Looper.myLooper()); 
            Message msg = handler.obtainMessage(1,1,1,"myself"); 
            handler. sendMessage(msg); 
            Looper.loop();  
        } 
        //Define the message processing class in the thread class 
        class ThreadHandler extends Handler{ 
            public ThreadHandler(Looper looper){ 
                super(looper); 
            } 
            public void handleMessage(Message msg){ 
                // Here, the Message in the MessageQueue in the thread is processed 
                //Here we return a message to the main thread 
                //Join the judgment to see if it is the message sent by the thread itself 
                if(msg.what == 1 && msg.obj.equals("myself")){ 
                    handler = new MyHandler(Looper.getMainLooper()); 
                    Message msg2 = handler.obtainMessage(1,1,1,"Report to the Lord Thread: I received the Message I sent to myself"); 
                    handler.sendMessage(msg2);                 
                } 
            } 
        } 
    } 
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325528918&siteId=291194637