Android Source Code Analysis (c)-->handlerthread

Source: Internet
Author: User

What's a handlerthread? When you view the definition of a class, there is a passage:

foranewathentocreate handler classes. Note that start() must still be called.

This means that the function of this class is to create a thread that contains looper.
So when do we need to use it? Join in the application to accomplish multiple tasks at the same time, so we will create multiple threads in the application. In order to facilitate communication between multiple threads, we use handler to implement inter-thread communication. This time we manually implemented a simplified version of multithreaded +handler is what we handlerthrea to do.

Let's first look at the basic usage of Handlerthread:

Handlerthread Mhandlerthread =NewHandlerthread ("Myhandlerthreand"); Mhandlerthread.start ();//created handler will be executed in the Mhandlerthread thread        FinalHandler Mhandler =NewHandler (Mhandlerthread.getlooper ()) {@Override             Public void Handlemessage(Message msg) {LOG.I ("Tag","received message:"+ msg.obj.toString ());        }        };        title = (TextView) Findviewbyid (r.id.title); Title.setonclicklistener (NewView.onclicklistener () {@Override             Public void OnClick(View v) {Message msg =NewMessage (); Msg.obj ="11111";                Mhandler.sendmessage (msg); msg =NewMessage (); Msg.obj ="2222";            Mhandler.sendmessage (msg); }        });

We first define a Handlerthread object, which is generated directly from the new method, to see how it is constructed:

publicHandlerThread(String name) {        super(name);        mPriority = Process.THREAD_PRIORITY_DEFAULT;    }

It can be known that handlerthread inherits from thread, so handlerthread is essentially a thread, and its construction method is mainly to do some initialization operation.

Then we call the Mhandlerthread.start () method, from the above we know that the Handlerthread class is actually a thread, and so its start method inside calls is certainly the thread's Run method, Let's look at the specific implementation of the Run method:

@Override    publicvoidrun() {        mTid = Process.myTid();        Looper.prepare();        synchronized (this) {            mLooper = Looper.myLooper();            notifyAll();        }        Process.setThreadPriority(mPriority);        onLooperPrepared();        Looper.loop();        mTid = -1;    }

We found that it internally called the Looper.prepate () method and the Loop.loop () method, and the child shoes familiar with the Android asynchronous messaging mechanism should know that a thread in the Android system actually corresponds to a Looper object, A MessageQueue object, and N handler objects, refer to: http://blog.csdn.net/qq_23547831/article/details/50751687

So through the run method, we can know that in the handlerthread thread we created we created the thread's Looper and MessageQueue;

It is important to note that it calls an empty implementation method before calling the Looper.loop () method: Onlooperprepared (), we can implement our own onlooperprepared () method, do some looper initialization operation;

In the Run method, when Mlooper is created, there is a notifyall (), and there is a wait () in Getlooper (). Because the mlooper is executed in a thread, and our handler is initialized in the UI thread, that is, we have to wait until Mlooper is created to properly return getlooper (); Wait (), notify () is to solve the synchronization problem of these two threads

Then we call the following:

// 创建的Handler将会在mHandlerThread线程中执行        finalnew Handler(mHandlerThread.getLooper()) {            @Override            publicvoidhandleMessage(Message msg) {                Log.i("tag""接收到消息:" + msg.obj.toString());            }        };

The Handlerthread Looper object is passed into the constructor of the handler, so the handler object is equivalent to a reference to the Handlerthread object in the Looper thread.

Then we call handler's SendMessage method to send the message, and in handler's Handlemessge method we can receive the message.

The last point to note is that we need to stop manually when we don't need this looper thread;

protectedvoidonDestroy() {        super.onDestroy();        mHandlerThread.quit();    }

Relatively speaking, Handlerthread is relatively simple, here to summarize:

    • Handlerthread is essentially a thread object, but its interior helps us create the thread's Looper and MessageQueue;

    • By Handlerthread we can not only implement the UI thread and child thread communication, but also can implement the communication between child thread and child thread;

    • Handlerthread need to be collected manually when not in use;

Android Source Code Analysis (c)-->handlerthread

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.