Android basics 02 -- thread security 4: handlerthread

Source: Internet
Author: User

Android UI operations are not thread-safe, and only the main thread can operate the UI. At the same time, the main thread has a certain time limit on UI operations (up to 5 seconds ). To perform some time-consuming operations (such as downloading and opening large files), Android provides some column mechanisms. The articles in the "android basics 02-thread security" series refer to a series of articles compiled by many online users and introduce the main methods. They are as follows:

Android basics 02 -- thread security 1: Definitions and Examples

Android basics 02 -- thread security 2: handler, message, and runnable

Android basics 02 -- thread security 3: Message, messagequeue, handler, Logoff

Android basics 02 -- thread security 4: handlerthread

Android basics 02 -- thread security 5: asynctask

In thread security, subthreads are used for processing to operate the UI of the main thread. In Android development, you can also use the following two methods:

Handlerthread

Asynctask

This article first introduces handlerthread.

Handlerthread inherits from thread, so it is essentially a thread. The difference with a normal thread is that it has a logoff member variable. This loose is actually the encapsulation of the message queue and the queue processing logic. Simply put, it is the message queue + message loop.
When we need a worker thread, instead of using it as a disposable consumable, we can use it if it is used out.

The usage is as follows:

Public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); handlerthread hthread = new handlerthread ("mythread"); hthread. start (); myhandler = new myhandler (hthread. getlooper (); message MSG = myhandler. obtainmessage (); MSG. sendtotarget (); // sends the message to the target object. The target object is the target object that generates MSG. } Class myhandler extends handler {public myhandler (Looper loader) {super (logoff);} public void handlemessage (Message MSG) {log. E ("this is a new thread ");}}

Start a new thread through handlerthread.
Note: handlerthread. Start () is required here; the thread can be started before handlerthread. getlooper () gets the looper of the current thread.

Handlerthread is relatively simple to use. It is also very easy to flip through its source code.

/** * 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. */public class HandlerThread extends Thread {    private int mPriority;    private int mTid = -1;    private Looper mLooper;    public HandlerThread(String name) {        super(name);        mPriority = Process.THREAD_PRIORITY_DEFAULT;    }        /**     * Constructs a HandlerThread.     * @param name     * @param priority The priority to run the thread at. 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;    }        /**     * Call back method that can be explicitly over ridden if needed to execute some     * setup before Looper loops.     */    protected void onLooperPrepared() {    }    public void run() {        mTid = Process.myTid();        Looper.prepare();        synchronized (this) {            mLooper = Looper.myLooper();            Process.setThreadPriority(mPriority);            notifyAll();        }        onLooperPrepared();        Looper.loop();        mTid = -1;    }        /**     * 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 looper has been initialized.       * @return The looper.     */    public Looper getLooper() {        if (!isAlive()) {            return null;        }                // If the thread has been started, wait until the looper has been created.        synchronized (this) {            while (isAlive() && mLooper == null) {                try {                    wait();                } catch (InterruptedException e) {                }            }        }        return mLooper;    }        /**     * Ask the currently running looper to quit.  If the thread has not     * been started or has finished (that is if {@link #getLooper} returns     * null), then false is returned.  Otherwise the looper is asked to     * quit and true is returned.     */    public boolean quit() {        Looper looper = getLooper();        if (looper != null) {            looper.quit();            return true;        }        return false;    }        /**     * Returns the identifier of this thread. See Process.myTid().     */    public int getThreadId() {        return mTid;    }}

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.