Android Source code parsing (iv)--> Handlerthread

Source: Internet
Author: User

Reprint please indicate the source: a column of Maple Leaf

In the previous article we explained the basic use of asynctast and the principle of implementation, and we know that Asynctask is implemented internally through a thread pool and handler. Asynchronous task operations are implemented through encapsulation of thread pools and handler. A lot of other Asynctask related content can be included in my Android source code parsing (iii) –> asynchronous task Asynctask

In this paper, we will explain handlerthread related concepts.

What is Handlerthread? The best way to understand a class is to look at the definition of a class, so let's take a look at how handlerthread is defined.

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 includes Looper.
So when do we need to use it? increased in the application where multiple tasks are completed 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 take a look at the basic use of handlerthread in the following way:

/** * Test handlerthread Basic Use * *Handlerthread Mhandlerthread =NewHandlerthread ("Myhandlerthreand"); Mhandlerthread.start ();//created handler will run in 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;    }

Be able to know that Handlerthread inherits from thread. So, Handlerthread is essentially a thread. The main construction method is 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. A thread, so its start method is called internally by the thread's Run method, and we look at the detailed implementation of its 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. Children's shoes familiar with the Android asynchronous messaging mechanism should be known. In the Android system, a thread is actually a Looper object, a MessageQueue object. and N Handler objects, detailed: Android source code parsing (ii) –> asynchronous message mechanism

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, and do some looper initialization operations.

In the Run method, when Mlooper is created, there is a notifyall (), and there is a wait () in Getlooper (). Because the mlooper runs in a thread. And our handler is initialized in the UI thread, that is, we have to wait until Mlooper is created, the ability to return Getlooper () correctly, wait (), notify () to resolve 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();    }

Well, the above is handlerthread related knowledge. Handlerthread is relatively simple. It's essentially a thread, but it just includes Looper and MessageQueue, and we'll wrap it up here.

Summarize:

    • Handlerthread is essentially a thread object. Just the internal help we created the thread of Looper and MessageQueue;

    • By Handlerthread we can not only implement the UI thread to communicate with the child thread, but also the child thread and the child thread.

    • The handlerthread need to be collected manually when not in use;

In addition to the Android source code parsing method is interested in my:
Android Source code parsing (i) –>android project build process
Android source code parsing (ii) –> asynchronous message mechanism
Android Source code parsing (iii) –> asynchronous task Asynctask

This article synchronizes to GitHub: Https://github.com/yipianfengye/androidSource, Welcome to star and follow

Android Source code parsing (iv)--> 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.