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

Keywords: Android uses 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. Includes 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 straightforward:


The main thread sends a message to the asynchronous thread, and the asynchronous thread receives the message after it sends a message to the main thread.


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

2. Start an asynchronous thread, create a looper in an asynchronous thread, and initialize the handler of an asynchronous thread.

3. The main thread gets the handler of the asynchronous thread (which 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 that is bound to the corresponding thread's message queue, and the Looper object of the corresponding thread is passed in the handler constructor.

2. Why to use the thread lock to handle, because the asynchronous thread start is not real-time, the main thread gets the asynchronous thread's handler when it is possible to be empty, if it is empty, you need to wait for the asynchronous thread to initialize the 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;/*** Send a message to a child thread using the handler test main 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            if(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() {if(Handler==NULL) {synchronized(Asyncthread.class) {//Inter-thread security                    if(Handler==NULL) {Try{//Gets the handler of the asynchronous thread is empty, releasing the lock, waiting for the asynchronous thread to initialize.                             Log.e(Handlersimpleactivity.class. Getsimplename (),                                    "gethandler Wait curthread ="                                            + Thread.CurrentThread(). GetName ());                            Asyncthread.class. Wait ();                        }Catch(Interruptedexception e) {E.printstacktrace ();                        }//Asynchronous thread handler initialization complete, the 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 ...



I Android rookie, please PAT Chase!!!


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

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.