[Android Notes] HandlerThread source code analysis, Android handlerthread

Source: Internet
Author: User

[Android Notes] HandlerThread source code analysis, Android handlerthread
Sometimes we need to create some resident sub-threads in the application to execute some computing tasks from time to time. At this time, we can consider using HandlerThread, which has the role of creating subthreads with message loops.
I. HanderThread usage exampleFirst, familiarize yourself with the general usage of HandlerThread. Create an Activity as follows:

Package com. example. handlethreaddemo; import android. app. activity; import android. OS. bundle; import android. OS. handler; import android. OS. handlerThread; import android. OS. logoff; import android. OS. message; import android. util. log; public class MainActivity extends Activity {private Looper mLooper; private MyHandler mHandler; private static final String TAG = "MainActivity"; private static class MyHandler extends Handler {public MyHandler (Looper looper) {super (logoff) ;}@ Overridepublic void handleMessage (Message msg) {switch (msg. what) {case 1: Log. I (TAG, "current Thread is" + Thread. currentThread (). getName () + ", TEST 1"); break; case 2: Log. I (TAG, "TEST 2"); break ;}}@ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); // create the HandlerThread object HandlerThread myHandleThread = new HandlerThread ("HandlerThread <sub-thread>"); // start HandlerThread ----> internally, the message loop myHandleThread is started. start (); // obtain loopermlothread = myHandleThread. getlooper(); // construct a Handler and pass in LoopermHandler = new MyHandler (mloler) in the sub-thread;/** Note: After the preceding steps, Handler binds looperand MessageQueue of the sub-thread. * That is to say, handleMessage is finally called by the sub-thread **/mHandler. sendEmptyMessage (1); Log. I (TAG, "current Thread is:" + Thread. currentThread (). getName ());}}

Construct the Handler object using the logoff object provided by HandlerThread, and then send messages to the Handler in the ui thread. The log is as follows:


It can be seen that the thread for sending messages is the UI thread, and the thread for processing messages is the subthread, that is, we A message loop is created in the Child thread.. In general, we always create Handler objects in the UI thread and use the default logoff provided by the interface component. This logoff is bound to the UI thread. Therefore, when we send messages to Handler in the thread, the final processing is carried out in the main thread. However, as mentioned in the beginning, we sometimes need to build a resident sub-thread to execute computing tasks from time to time. In this case, it is very useful to create a message loop in the sub-thread.
Ii. HandlerThread source code analysisHandlerThread source code is very streamlined. HandlerThread inherits from java. lang. Thread and encapsulates the logoff object:
Int mPriority; // int mTid =-1; // The thread flag is low.mlogoff; // message loop

Thread priority can be injected through the constructor. The default priority is Process. THREAD_PRIORITY_DEFAULT.
 public HandlerThread(String name, int priority) {        super(name);        mPriority = priority;    }

The core logic is the run method (the run method of the Thread class ):
Public void run () {mTid = Process. myTid (); logoff. prepare (); // create a logoff object synchronized (this) {mLooper = loni. myLooper (); // obtain the Looper policyall ();} Process bound to this thread. setThreadPriority (mPriority); onLooperPrepared (); // callback interface, which is empty by default. Logoff. loop (); // start the message loop ---> may be blocked mTid =-1 ;}

You can use the getlogoff method to obtain the logoff object:
Public Looper getLooper () {if (! IsAlive () {// return null for thread death;} // If the thread has been started, wait until the looper has been created. synchronized (this) {while (isAlive () & mloiter = null) {try {wait (); // asynchronously wait for Logoff to be ready} catch (InterruptedException e) {}} return mLooper ;}

If logoff is not ready when the getlogoff method is called, the thread will be blocked until the logoff object is ready. You can call the quit method to terminate the message loop:
Public boolean quit () {Looper looper = getLooper (); if (looper! = Null) {loit. quit (); // internally call the quit return true;} return false ;}

Note: lofter class is familiar to everyone. Here I will give you a brief introduction (Handler and Looper have been written before): Looper. the prepare method will create a Looper object (the Looper class constructor is private and cannot be new) and place it in ThreadLocal, meaning the local variable of the thread:
public static void prepare() {        prepare(true);    }    private static void prepare(boolean quitAllowed) {        if (sThreadLocal.get() != null) {            throw new RuntimeException("Only one Looper may be created per thread");        }        sThreadLocal.set(new Looper(quitAllowed));    }

Then return The logoff bound to this thread through the logoff. mylogoff method, which is exactly the created Logoff:
public static Looper myLooper() {        return sThreadLocal.get();    }

The logoff. loop Method starts a message loop and keeps Retrieving messages from its encapsulated Message Queue MessageQueue, which is executed by Handler.

public static void loop() {        final Looper me = myLooper();        if (me == null) {            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");        }        final MessageQueue queue = me.mQueue;        // Make sure the identity of this thread is that of the local process,        // and keep track of what that identity token actually is.        Binder.clearCallingIdentity();        final long ident = Binder.clearCallingIdentity();        for (;;) {            Message msg = queue.next(); // might block            if (msg == null) {                // No message indicates that the message queue is quitting.                return;            }            // This must be in a local variable, in case a UI event sets the logger            Printer logging = me.mLogging;            if (logging != null) {                logging.println(">>>>> Dispatching to " + msg.target + " " +                        msg.callback + ": " + msg.what);            }            msg.target.dispatchMessage(msg);            if (logging != null) {                logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);            }            // Make sure that during the course of dispatching the            // identity of the thread wasn't corrupted.            final long newIdent = Binder.clearCallingIdentity();            if (ident != newIdent) {                Log.wtf(TAG, "Thread identity changed from 0x"                        + Long.toHexString(ident) + " to 0x"                        + Long.toHexString(newIdent) + " while dispatching to "                        + msg.target.getClass().getName() + " "                        + msg.callback + " what=" + msg.what);            }            msg.recycle();        }    }

When no message is available, the message queue is blocked.
The above is all the content of HandlerThread.





I saw an advertisement on TV (for Android tablets in the United States) saying that the original price was 3500 yuan.

Yes, but be sure not to give them money and say yes in advance. You can find a way to obtain evidence and remember to never give a dime. They all said they should not pay a penny.


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.