Android uses handler to send messages between threads (between the main thread and child threads), (between child threads and child threads)

Source: Internet
Author: User
Tags message queue

Keyword:android using handler to send messages between threads (between the main thread and child threads), (between child threads and child threads)


It is believed that everyone usually has the use of asynchronous threads to send messages to the main thread (UI thread).

This paper mainly studies handler's message sending.

Contains the main thread to send messages to the child threads, and the child threads to send messages to each other.


One, the mainline Cheng thread sends the message.


The implementation process is relatively simple:


The main thread sends a message to an asynchronous thread. After the asynchronous thread receives the message, it sends a message to the main thread again.


1. Initializes the handler of the main thread to receive messages for the child threads.

2. Start the asynchronous thread. Creates a looper in an asynchronous thread and initializes the handler of an asynchronous thread.

3. The main thread gets the handler of the asynchronous thread (this involves the knowledge of synchronization between threads). and sends a message to the asynchronous thread.

4. When the asynchronous thread handler receives the message, it gets the handler of the main thread and sends a message to the main thread.

5. The main thread receives a message from an asynchronous thread.


Note:

1. The main thread handler, or asynchronous thread handler, refers to a handler object bound to the corresponding thread's message queue, and the Looper object in the handler constructor is passed in to the corresponding thread.

2. Why the thread lock is used for processing because the asynchronous thread start is not real-time. When the main thread gets the handler of an asynchronous thread, it may be empty, assuming it is empty, and waits for the async thread to initialize handler first.


On the code:

 PackageCom.example.chen.myapplication;ImportAndroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.os.Looper;ImportAndroid.os.Message;ImportAndroid.util.Log;/*** Use handler test main thread to send message to child thread * @authorChen */Public classHandlersimpleactivityextendsActivity {PrivateHandlerMainHandler;    @Override    protected voidonCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        //Start asynchronous Thread        FinalAsyncthread Asyncthread =NewAsyncthread ();        Asyncthread.start ();        //Initialize the handler of the main thread        MainHandler=NewHandler (Looper.Mylooper(), NewHandler.callback () {@Override            Public BooleanHandlemessage(Message msg) {//The main thread receives the message                Log.e(Handlersimpleactivity.class. Getsimplename (),                        "MainHandler Receiver Message curthread ="                                + Thread.CurrentThread(). GetName ());return false;            }        });        //Gets the handler of the asynchronous thread        Handler Handler = Asyncthread.gethandler ();if(Handler! =NULL) {Log.e(Handlersimpleactivity.class. Getsimplename (),                    "Mainthread Send Message curthread ="                            + Thread.CurrentThread(). GetName ());            //Send a message to an asynchronous thread            Handler.sendemptymessage (0);        }    }/*** Async Thread     */    Private ClassAsyncthreadextendsThread {PrivateHandlerHandler;        @Override        Public voidRun() {Super. Run ();            Log.e(Handlersimpleactivity.class. Getsimplename (),                    "Asyncthread Start curthread ="                            + Thread.CurrentThread(). GetName ());            Looper.Prepare(); //Initialize the message loop queue for an asynchronous thread            off(Handler==NULL) {synchronized(Asyncthread.class) {//Inter-thread security//Add a handler to the message loop queue for the asynchronous thread                    Handler=NewHandler (Looper.Mylooper(), NewHandler.callback () {@Override                        Public BooleanHandlemessage(Message msg) {//Async thread receives message                            Log.e(Handlersimpleactivity.class. Getsimplename (),                                    "Asynchandler Receiver Message curthread ="                                            + Thread.CurrentThread(). GetName ());                            //asynchronous thread sends a message to the main thread                            Log.e(Handlersimpleactivity.class. Getsimplename (),                                    "Asyncthread Send Message curthread ="                                            + Thread.CurrentThread(). GetName ());                            MainHandler. Sendemptymessage (0);return false;                        }                    });                    //Asynchronous thread handler initialization complete                    Log.e(Handlersimpleactivity.class. Getsimplename (),                            "Asynchandler inited curthread ="                                    + Thread.CurrentThread(). GetName ());                    //Release lock                    Asyncthread.class. Notifyall ();                }} Looper.Loop();        }/*** Get handler of asynchronous Threads         * @return */         PublicHandlerGetHandler() {off(Handler==NULL) {synchronized(Asyncthread.class) {//Inter-thread security                    if(Handler==NULL) {Try{Gets the handler of the asynchronous thread is empty. Releases the lock, waiting for asynchronous thread initialization to complete.

Log.e(Handlersimpleactivity.class. Getsimplename (), "gethandler Wait curthread =" + Thread.CurrentThread(). GetName ()); Asyncthread.class. Wait (); }Catch(Interruptedexception e) {E.printstacktrace (); }//Asynchronous thread handler initialization is complete. Main thread continues Log.e(Handlersimpleactivity.class. Getsimplename (), "GetHandler Notified Curthread =" + Thread.CurrentThread(). GetName ());returnHandler; }Else{returnHandler; } } }Else{returnHandler; } } }}


The result:



Second, use handler to send messages to each other between sub-threads:


July 26, 2015 19:47:31 wait for next update (*^__^*) hehe ...


Updated November 9, 2015. Inter-thread communication can be used with handlerthread. Interested friends can look at the source code. Just one class. The code is not much, the system's API is written to be robust.

About Handlerthread. You can read the blog:

http://blog.csdn.net/a740169405/article/details/50257001


My Android rookie, please correct me!!


Android uses handler to send messages between threads (between the main thread and child threads), (between child threads and 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.