Handlerthread is a special thread, that is, looper thread, since there is looper, then we can use this looper to
Create a handler to interact with it, such as you can send a message to it in the UI thread through the handler object associated with it. Handlerthread
It is generally possible to perform certain background operations, such as reading and writing files (in this handlerthread instead of the UI thread). Since it's still a thread,
Like a normal thread, you start it by calling its start () method. It's just a helper class that Android has packaged for us, and its source code is fairly concise and we
Here's a look, it's simple.
As usual, let's look at the fields and ctor:
intmpriority;//Thread PriorityintMtid =-1///thread ID Looper mlooper;//thread-associated Looper PublicHandlerthread (String name) {//provides a name for easy debugSuper(name); Mpriority=Process.thread_priority_default;//not provided, use default priority}/*** Constructs a handlerthread. * @paramname *@paramPriority the "to run" of the thread at. The value supplied must is from * {@linkandroid.os.Process} and not from Java.lang.Thread. */ PublicHandlerthread (String name,intPriority ) { Super(name); Mpriority=priority;//Use user-provided priorities, based on Linux priority, value between [ -20,19]}
The code is simple, the relevant analysis is written directly in the code comments, it is important to note that the priority here is based on Linux priorities, not Java Thread
Class of min_priority,norm_priority,max_priority, please pay attention to distinguish (in fact, carefully read the method of doc).
Next look at the key 3 methods of this class:
/*** Call back Method The can is explicitly overridden if needed to execute some * setup before Looper loops. */ protected voidonlooperprepared () {//callback method, if you wish you can Override your logic, and it executes before loop starts} @Override Public voidrun () {Mtid=Process.mytid (); Looper.prepare (); This method, as we described earlier, creates a Looper object associated with a threadsynchronized( This{///Enter the synchronization block, when Mlooper becomes available for use, call Notifyall to notify other threads that might block on the current object Mlooper=Looper.mylooper (); Notifyall (); } process.setthreadpriority (mpriority); Set thread priority onlooperprepared (); Call the callback function Looper.loop (); Start Loop Mtid=-1;//reset is invalid value}/*** This method returns the Looper associated with this thread. If This thread isn't been started * or for any reason are isAlive () returns False, this method would return null. If this thread * have been started, this method would block until the Looper has been initialized. * @returnThe looper. */ PublicLooper Getlooper () {if(!isAlive ()) {//If the thread is not in the alive state then directly returns NULL, it is possible that you forgot to adjust the Start method ... return NULL; } //If The thread has been started, wait until the Looper have been created. synchronized( This) { while(IsAlive () && Mlooper = =NULL{//Enter the sync block, wait indefinitely when the condition is not met,Try{//until Mlooper is set to a valid value to exit while (or the thread State may not be satisfied); wait (); The Notifyall in the Run method is used to wake up the}Catch(interruptedexception e) {//Ignore interruptedexception}}} returnmlooper;//Last Return to Mlooper, at which time the valid values are guaranteed. }
Remember to call its start () method when you are new to a Handlerthread object, and then you can then call its Getlooper () method to new a handler object,
Finally you can use this handler object to send messages to and from Handlerthread to make it work for you.
Finally, 2 exit Handlerthread methods, in fact, corresponding to the Looper 2 exit methods:
/*** quits the handler thread ' s looper. * <p> * Causes the handler thread ' s looper to terminate without processing any * More messages in the MESSAG E queue. * </p><p> * Any attempt to post messages to the queue after the Looper are asked to quit would fail. * For example, the {@linkhandler#sendmessage (Message)} method would return false. * </p><p class= "NOTE" > * Using This method may is unsafe because some messages may not be delivered * Before the looper terminates. Consider using {@link#quitSafely} instead to ensure * this all pending work are completed in an orderly manner. * </p> * *@returnTrue If the looper looper have been asked to quit or False if the * thread had not yet started running. * * @see#quitSafely*/ Public Booleanquit () {Looper Looper=getlooper ();//Note this is called Getlooper instead of directly using Mlooper,if(Looper! =NULL{//Because mlooper may not have been initialized yet, the calling method can be looper.quit (); Wait for initialization to complete. return true; } return false; } /*** quits the handler thread ' s looper safely. * <p> * Causes the handler thread ' s looper to terminate as soon as all remaining messages * in the message q Ueue that is already due to be delivered has been handled. * Pending delayed messages with due times on the future won't be delivered. * </p><p> * Any attempt to post messages to the queue after the Looper are asked to quit would fail. * For example, the {@linkhandler#sendmessage (Message)} method would return false. * </p><p> * If the thread has not been started or have finished (that's if * {@link#getLooper} returns null), then false is returned. * Otherwise The Looper is asked to quit and true is returned. * </p> * *@returnTrue If the looper looper have been asked to quit or False if the * thread had not yet started running. */ Public Booleanquitsafely () {Looper Looper=Getlooper (); if(Looper! =NULL) {looper.quitsafely (); return true; } return false; }
Through the code we can see that the interior is delegate to the Looper object, and Looper we have introduced in the previous, interested students can look at the previous analysis or
Check out these 2 methods of Doc, written in very detailed.
This simple Handy class is even finished. In the actual development, if you just want to do some background operation (short, such as put some settings file load
in memory, instead of updating the UI, you can prioritize using handlerthread instead of Asynctask.
Next, prepare to analyze the data storage mechanism provided by AndroidSharedPreferences,敬请期待。。。