Android HandlerThread source code analysis and android source code analysis

Source: Internet
Author: User

Android HandlerThread source code analysis and android source code analysis
HandlerThread introduction:

We know that the Thread is a consumable item. After the Thread executes a time-consuming task, the Thread will be automatically destroyed. If I have another

Time-consuming tasks need to be executed. We have to re-create a thread to execute the time-consuming task. However, there is a performance problem in this way: It is very expensive to create and destroy threads multiple times.

System resource. To understand this problem, we can build a loop Thread low.thread by ourselves. When a time-consuming task is put into this loop Thread, the Thread execution consumption is

After the task is executed, the cyclic thread is in the waiting state until the next time-consuming task is put in. This avoids multiple Thread creation.

Performance problems. Maybe you can build a loop thread by yourself, but I can tell you the good news that there is actually a loop thread framework in the Aandroid SDK.

. Now you only need to know how to use it! Of course, it's HandlerThread, our main character today! Next, please play HandlerThread and applaud ~~

The parent class of HandlerThread is Thread, so HandlerThread is actually a Thread, but it helps you implement a loose loop internally. Then we

Let's take a look at how Handler works!

[Reprinted with the source code: Android HandlerThread source code analysis CSDN ruins tree]

HandlerThread usage steps: 1. Create an Instance Object
HandlerThread handlerThread = new HandlerThread("handlerThread");

The preceding parameters can be any string. The parameter is used to mark the name of the current thread.

2. Start the HandlerThread
handlerThread.start();

At this point, we have built a loop thread. So you may doubt, how can I put a time-consuming asynchronous task into the HandlerThread for execution? Of course there is a solution. Next, let's look at the third part.

3. Construct a cyclic Message Processing Mechanism
Handler subHandler = new Handler (handlerThread. getLooper (), new Handler. callback () {@ Override public boolean handleMessage (Message msg) {// implement your own Message processing return true ;}});

Step 3: Create a Handler object, set the logoff object in the HandlerThread above as the Handler parameter, and then rewrite

HandlerMessage method to process time-consuming tasks.

Summary:The preceding three steps must be strictly followed. At this point, we can call subHandler to send time-consuming tasks to the thread in the form of messages.

HandlerThread. The implication is that the handlerMessage method in the Callback interface class of subHandler is actually executed in the work thread.

HandlerThread instance:
Package com. example. handlerthread; import android. app. activity; import android. OS. bundle; import android. OS. handler; import android. OS. handlerThread; import android. OS. message; import android. view. view; import android. view. view. onClickListener; import android. widget. button; import android. widget. textView; public class MainActivity extends Activity {private Handler mSubHandler; private TextView textView; private Button button; private Handler. callback mSubCallback = new Handler. callback () {// The implementation of this interface is to process asynchronous time-consuming tasks. Therefore, this method is executed in the subthread @ Override public boolean handleMessage (Message msg) {switch (msg. what) {case 0: Message msg1 = new Message (); msg1.what = 0; msg1.obj = java. lang. system. currentTimeMillis (); mUIHandler. sendMessage (msg1); break; default: break;} return false ;};@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); textView = (TextView) findViewById (R. id. textView); button = (Button) findViewById (R. id. button); HandlerThread workHandle = new HandlerThread ("workHandleThread"); workHandle. start (); mSubHandler = new Handler (workHandle. getLooper (), mSubCallback); button. setOnClickListener (new OnClickListener () {@ Override public void onClick (View v) {// place the asynchronous time-consuming task to mSubHandler in HandlerThread. sendEmptyMessage (0 );}});}}
HandlerThread source code analysis HandlerThread Constructor
/*** Handy class for starting a new thread that has a logoff. the logoff can then be * used to create handler classes. note that start () must still be called. */public class HandlerThread extends Thread {// Thread priority int mPriority; // The current Thread id int mTid =-1; // The logoff object logoff mlogoff held by the current Thread; // constructor public HandlerThread (String name) {// call the default method of the parent class to create the thread super (name); mPriority = Process. THREAD_PRIORITY_DEFAULT;} // construction method with priority parameter public HandlerThread (String name, int priority) {super (name ); mPriority = priority ;}...............}

Analysis: A description is given at the beginning of this class: this class is used to create a thread with a logoff loop, and The logoff object is used to create a Handler object. It is worth noting that

Before the object, you must call the start () method to start the thread. Some people may have questions here? Why do I need to call the start () method before creating a Handler? We will answer your questions later.

The preceding Code annotations are clear. The HandlerThread class has two constructor methods, except that the priority parameter of the current thread is set. You can set priority based on your situation.

Level, you can also use the default priority.

HandlerThrad run Method
Public class HandlerThread extends Thread {/*** Call back method that can be explicitly overridden if needed to execute some * setup before low.loops. */protected void onLooperPrepared () {}@ Override public void run () {// obtain the id of the current thread mTid = Process. myTid (); // prepare the logoff condition. prepare (); // hold the lock mechanism to obtain the logoff object synchronized (this) {mloed = loni. myLooper (); // send a notification. The mLooper object has been successfully created in the current thread. Here, it mainly notifies ge Wait policyall ();} // sets the priority of the current thread. setThreadPriority (mPriority); // The implementation body of this method is empty. The subclass can implement this method, which is used to prepare for the thread loop. Of course, the subclass can also not be implemented. OnLooperPrepared (); // start loop logoff. loop (); mTid =-1 ;}}

Analysis: the comments in the above Code have been clearly written. The main function of the above run method is to call lorule. prepare and lorule. loop To build a loop thread. It is worth mentioning

Yes. The onLooperPrepared method is called before the loop is started in the run method. The implementation of this method is empty. You can implement this method in the subclass. The function of this method is

Perform initialization before the thread loop. You can also choose not to implement this method, depending on your needs. It can also be seen that Google engineers also consider code scalability when writing code. Niu B!

Other HandlerThread Methods getLooper get The logoff object of the current thread
/*** This method returns the Looper associated with this thread. if this thread not been started * or for any reason is isAlive () returns false, this method will return null. if this thread * has been started, this method will block until the loginhas been initialized. * @ return The logoff. */public Looper getLooper () {// if the thread is not alive, null if (! IsAlive () {return null;} // If the thread has been started, wait until the looper has been created. // If the thread has been started but the logoff has not yet been created, wait until you know that The logoff has been successfully created synchronized (this) {while (isAlive () & mLooper = null) {try {wait () ;}catch (InterruptedException e) {}} return mlotion ;}

Analysis: in fact, the English comment at the beginning of the method has been clearly explained: The main function of this method is to obtain the mlogoff object in the current HandlerThread.

First, judge whether the current thread is alive. If it is not alive, null is returned directly. Second, if the current thread is alive, check whether the mlo variable of the thread is null. If it is

Null indicates that the current thread has been successfully created, but it has not been able to create a logoff object. Therefore, the wait method is called to wait. After the policyall method in the run method is called

The wait method of the current thread is notified to wait for the end and jump out of the loop to obtain the value of the mLooper object.

Summary:There is a synchronization problem when obtaining the mLooper object. The mLooper value can be obtained only after the thread is successfully created and the Looper object is also created. Wait for the notifyAll method in the wait and run methods to complete the synchronization.

Quit ends the loop of the current thread
/*** Quits the handler thread's logoff. * <p> * Causes the handler thread's logoff to terminate without processing any * more messages in the message queue. * </p> <p> * Any attempt to post messages to the queue after the logoff is asked to quit will fail. * For example, the {@ link Handler # sendMessage (Message)} method will return false. * </p> <p class = "note"> * Using this method may be unsafe becau Se some messages may not be delivered * before the looper terminates. consider using {@ link # quitSafely} instead to ensure * that all pending work is completed in an orderly manner. * </p> ** @ return True if the logoff has been asked to quit or false if the * thread had not yet started running. ** @ see # quitSafely */public boolean quit () {Looper loit = getLooper (); if (loit! = Null) {looper. quit (); return true;} return false;} // Security Exit loop public boolean quitSafely () {Looper lofel= getLooper (); if (looper! = Null) {looper. quitSafely (); return true;} return false ;}

Analysis: There are two methods to exit the current thread, one is safe, and the other is not safe. What is the difference between the two? The quitSafely method is more efficient than the quit method, but is safer. The specific choice depends on the specific project.

Summary:

1. HandlerThread is suitable for building loop threads.

2. the start method must be called after Handler is created as the executor of the HandlerThread message, because the logoff parameter required for Handler creation is obtained from the HandlerThread class, the value assignment of The logoff object is created in the run method of HandlerThread.

3. For how to use HandlerThread and Service, refer to another blog: Android IntentService source code analysis.

[Reprinted with the source code: Android HandlerThread source code analysis CSDN ruins tree]

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.