Android source code parsing (3) --) HandlerThread

Source: Internet
Author: User

Android source code parsing (3) --) HandlerThread

What is HandlerThread? When viewing the definition of a class, there is a paragraph like this:

Handy class for starting a new thread that has a looper. The looper can then be used to create handler classes. Note that start() must still be called.

This class is used to create a thread containing logoff.
So when do we need it? To implement multiple tasks at the same time, we will create multiple threads in the application. To facilitate communication between multiple threads, Handler is used to implement inter-thread communication. At this time, the simple version of the multi-thread and Handler we implemented manually is what we have to do with HandlerThrea.

Next, let's take a look at the basic usage of HandlerThread:

HandlerThread mHandlerThread = new HandlerThread ("myHandlerThreand"); mHandlerThread. start (); // The created Handler will execute final Handler mHandler = new Handler (mHandlerThread. getLooper () {@ Override public void handleMessage (Message msg) {Log. I ("tag", "received message:" + msg. obj. toString () ;}}; title = (TextView) findViewById (R. id. title); title. setOnClickListener (new View. onClickListener () {@ Override public void onClick (View v) {Message msg = new Message (); msg. obj = "11111"; mHandler. sendMessage (msg); msg = new Message (); msg. obj = "2222"; mHandler. sendMessage (msg );}});

We first define a HandlerThread object, which is generated directly by using the new method. view its constructor method:

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

We can know that HandlerThread inherits from Thread, so HandlerThread is essentially a Thread, and its constructor mainly performs initialization operations.

Then we call mHandlerThread. from the start () method, we know that the HandlerThread class is actually a Thread and a Thread, so the start method must call the Thread's run method internally, let's take a look at the specific implementation of its run method:

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

We found that logoff is called internally. prepate () method and Loop. loop () method. It should be known that a thread in the android system corresponds to a logoff object, a MessageQueue object, and N Handler objects.

So through the run method, we can know that in the HandlerThread we created, we created the logoff and MessageQueue of this thread;

It is worth noting that it is calling logoff. the loop () method previously calls an empty implementation method: onLooperPrepared (). We can implement our own onLooperPrepared () method and perform some looperinitialization operations;

In the run method, when the mLooper creation is complete, there will be a policyall (), and a wait () in getLooper (). Why? Because mloler is executed in a thread, and our handler is initialized in the UI thread, that is, we must wait until the mLooper creation is complete to correctly return getLooper (); wait () and notify () are used to solve the synchronization problem between the two threads.

Then we call:

// The created Handler will execute final Handler mHandler = new Handler (mHandlerThread. getLooper () {@ Override public void handleMessage (Message msg) {Log. I ("tag", "received message:" + msg. obj. toString ());}};

The Handler constructor passes in the logoff object of HandlerThread, so the Handler object is equivalent to a reference containing the logoff object in the HandlerThread.

Then, we call the sendMessage method of handler to send a message. In Handler's handleMessge method, we can receive the message.

At last, we need to manually stop the logoff thread;

protected void onDestroy() {        super.onDestroy();        mHandlerThread.quit();    }

HandlerThread is relatively simple. Here we will summarize:

HandlerThread is essentially a Thread object, but it helps us to create the logoff and MessageQueue of this Thread internally;

Through HandlerThread, we can not only implement the communication between the UI thread and the sub-thread, but also implement the communication between the sub-thread and the sub-thread;

HandlerThread needs to be manually recycled when it is not needed;

Related Article

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.