HandlerThread is a special Thread, that is, a thread with logoff. Since there is logoff, we can use this logoff.
Create a Handler to interact with it. For example, you can send messages to the Handler object associated with it in the UI thread for processing. HandlerThread
Generally, it can be used to perform certain operations on the background, such as reading and writing files (in this HandlerThread rather than in the UI thread ). Since it is still a Thread
Like a general Thread, it should also be started by calling its start () method. It is just a Helper class encapsulated by Android for us. Its source code is quite concise, and we
Let's take a look at it. It's very simple.
As in the past, let's take a look at fields and cins:
Int mPriority; // thread priority int mTid =-1; // thread id low.mlogoff; // The low.public HandlerThread (String name) associated with the thread {// provide a name, facilitate debug super (name); mPriority = Process. THREAD_PRIORITY_DEFAULT; // if not provided, use the default priority}/*** Constructs a HandlerThread. * @ param name * @ param priority The priority to run the thread. the value supplied must be from * {@ link android. OS. process} and not from java. lang. thread. */public HandlerThread (String name, int priority) {super (name); mPriority = priority; // use the user-provided priority, based on the linux priority, value Range: [-20, 19}
The code is very simple. Relevant Analysis is directly written in the code comment. It is worth noting that the priority here is based on the linux priority, rather than the Java Thread
MIN_PRIORITY, NORM_PRIORITY, MAX_PRIORITY, and so on in the class. Pay attention to distinction (in fact, read the doc of the method carefully ).
Next, let's take a look at the three key methods of this class:
/*** Call back method that can be explicitly overridden if needed to execute some * setup before low.loops. */protected void onLooperPrepared () {// callback method. If you want to Override your logic, execute it before the loop starts.} @ Override public void run () {mTid = Process. myTid (); logoff. prepare (); // this method is described earlier. The logoff object synchronized (this) associated with the thread will be created {// enter the synchronization block. When mlogoff becomes available, call policyall to notify other threads that may block the current object. Mylogoff (); policyall ();} Process. setThreadPriority (mPriority); // set the thread priority onLooperPrepared (); // call the callback function looper. loop (); // start loop mTid =-1; // the reset is the invalid value}/*** This method returns the lovesassociated 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 unti L the logghas been initialized. * @ return The loggability. */public loggability getloggability () {if (! IsAlive () {// If the thread is not in the alive status, null is returned directly. It is possible that you forgot to call the start method... Return null;} // If the thread has been started, wait until the loginhas been created. synchronized (this) {while (isAlive () & mloiter = null) {// enter the synchronization block. when the conditions are not met, the system waits infinitely, try {// exit while (of course, the thread status may not be satisfied) until mlogoff is set to a valid value; wait (); // The policyall in the run method is used to wake up} catch (InterruptedException e) {// ignore InterruptedException }}return mlotion; // finally return mLooper, it can be a valid value.}
When you create a new HandlerThread object, remember to call its start () method. Then you can call its getLooper () method to create a new Handler object,
Finally, you can use this Handler object to send messages to HandlerThread to make it work for you.
Finally, let's look at the two methods to exit HandlerThread. In fact, they correspond to the two exit methods of Logoff:
/*** 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 = getloit (); // call getloit here Instead of using mloiter directly, if (loiter! = Null) {// because mLooper may not have been initialized yet, you can call looper. quit (); // wait until the initialization is complete. Return true;} return false;}/*** Quits the handler thread's logoff safely. * <p> * Causes the handler thread's logoff to terminate as soon as all remaining messages * in the message queue that are already due to be delivered have been handled. * Pending delayed messages with due times in the future will not be delivered. * </p> <p> * Any attempt to post messages to the queue after the lotempis Asked to quit will fail. * For example, the {@ link Handler # sendMessage (Message)} method will return false. * </p> <p> * If the thread has not been started or has finished (that is if * {@ link # getloted} returns null), then false is returned. * Otherwise the logoff is asked to quit and true is returned. * </p> ** @ return True if the loginloginhas been asked to quit or false if the * thread ha D not yet started running. */public boolean quitSafely () {Looper loning = getLooper (); if (looper! = Null) {looper. quitSafely (); return true;} return false ;}
Through the code, we can see that all of them are delegate to the logoff object, and we have also introduced the logoff in the previous section. If you are interested, you can refer to the previous analysis or
View the doc of the two methods and write them in detail.
So far, this simple Handy class is completely analyzed. In actual development, if you only want to perform some background operations (for example, load
To the memory), instead of updating the UI, you can use HandlerThread instead of AsyncTask first.
Next, we will analyze the data storage mechanism provided by Android.SharedPreferences...