Handler Thread for Android Threads

Keywords: Android snapshot

Summary

HandlerThread is a subclass of Thread and another thread form provided in Android.

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 is the description of the official class. Say that this class is a thread with Looper, the looper is used to create handler usage. Remember to call the start() method to start.

I wipe, there are threads, there is looper, this is not what we originally claimed to build handler message system in sub-threads need?

Source code analysis

Take a look at the thread core run() method source code:

 @Override
public void run() {
    mTid = Process.myTid(); //Get the id of the thread
    Looper.prepare();
    synchronized (this) {  // The reason for using synchronous code block is to deal with the synchronization problem of getLooper() and ensure the acquisition of looper.
        mLooper = Looper.myLooper();
        notifyAll(); //After obtaining, notify getLooper()
    }
    Process.setThreadPriority(mPriority); //Setting Thread Priority
    onLooperPrepared(); 
    Looper.loop();
    mTid = -1;
}
  • Looper.prepare() creates Looper and MessageQueue
  • Then the call to Looper.loop() loops the message system.
  • onLooperPrepared() is an empty method body, and subclasses can override this method to do pre-loop operations on threads.

Take another look at the getLooper() source code:

public Looper getLooper() {
    if (!isAlive()) { 
        return null;
    }

    // If the thread has been started, wait until the looper has been created.
    //If the thread is alive but the mLooper is empty, enter the wait and wait for the mLooper to be created
    //Here the wait method and notifyAll in run method realize thread synchronization
    synchronized (this) {  
        while (isAlive() && mLooper == null) { 
            try {
                wait();
            } catch (InterruptedException e) {
            }
        }
    }
    return mLooper;
}

Obviously, the purpose of this Handler Thread is to let us create a Handler, and then all task operations are successfully transferred to Handler for processing.
Notice, however, that the Handler message processing is running in a sub-thread.

usage

Create handler in the main thread and simply simulate how Handler Thread works

  @Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Create Handler Thread
    HandlerThread handlerThread = new HandlerThread("handlerThread");
    // You must call the start() method to execute the run method body
    handlerThread.start();
    //Get looper for this thread
    Looper looper = handlerThread.getLooper();
    //Create the Handler corresponding to this looper
    handler = new Handler(looper) {
        @Override
        public void handleMessage(Message msg) {
            Log.d("smart", "Current threads:" + Thread.currentThread().getName());
            if (msg.what == 2) {
                Log.d("smart", "handleMessage: Delay message received 2");
            }
        }
    };
    Message message = Message.obtain();
    message.what = 2;
    handler.sendMessage(message);
}

QQ snapshot 20170519162157.png

Since this handler callback runs in a sub-thread, if you want to update the UI, you can use the default looper of the main thread to do so. This problem has happily shifted to the problem of sub-thread updating the UI.

In addition, HandlerThread provides a way to exit the message loop and stop the execution of tasks.

  • quit()
  • quitSafely()

summary

Handler Thread is essentially a thread, but this thread adds the mechanism of Handler message asynchronous processing.
So what's the benefit of this versus the normal thread creation?

  • Handler Thread comes with Looper, which allows him to reuse the current thread many times through messages and saves money.
  • The Looper in Handler class provided by android system binds the message queue of UI threads by default. For non-UI threads, they want to use message mechanism, so Handler Thread is on the stage, and it does not interfere with or block UI threads.
  • In one case, threads have a message queue mechanism, and the control order of the task is handed over to the excellent Handler asynchronous message mechanism, which is easy to manage.
  • HanlderThread is used in IntentService in Android

Posted by ballouta on Thu, 27 Jun 2019 16:25:33 -0700