Android HandlerThread使用介紹以及源碼解析

1. 前言

首先,看一下官方對HandlerThread的解釋:java

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.複製代碼

翻譯中文爲:HandlerThread 是一個包含Looper的Thread,這個 Looper 能夠被用來建立 Handler,start方法必須被調用。android

咱們先來看看HandlerThread的特色:express

  • HandlerThread繼承Thread,本質仍是線程類;
  • HandlerThread內部建立looper對象,這個Looper對象能夠被用來建立Handler,經過looper循環,能夠在handleMessage方法中執行耗時任務。
  • HandlerThread必須先調用HandlerThread.start()方法。

2.使用方法

1)建立HandlerThread對象apache

handlerThread = new HandlerThread("refreash");複製代碼

2)啓動HandlerThread,建立Looperbash

handlerThread.start();複製代碼

HandlerThread必須先調用HandlerThread.start()方法,隨後Thread會調用run方法,建立Looper對象。app

3)HandlerThread內部建立Looper,用來新建handler對象,發送消息less

handler = new MyHandler(handlerThread.getLooper());
handler.sendMessage(handler.obtainMessage());複製代碼

4)handleMessage處理耗時任務ide

private class MyHandler extends Handler {
        public MyHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            handleIntent();
            sendMessage(handler.obtainMessage());
        }
    }複製代碼

3.具體使用代碼

package com.test.cyf;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.widget.TextView;

public class MainActivity extends Activity {

    private TextView amount;

    /**
     * 子線程
     */
    private MyHandler handler;

    private int size = 0;

    private HandlerThread handlerThread;

    private class MyHandler extends Handler {
        public MyHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            handleIntent();
            sendMessage(handler.obtainMessage());
        }
    }

    /**
     * 主線程刷新UI
     */
    private Handler uiHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            amount.setText(size + "");
            super.handleMessage(msg);
        }
    };


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

        initView();
        loadData();
    }

    /**
     * 初始化view
     */
    private void initView() {
        amount = (TextView) findViewById(R.id.amount);
    }

    /**
     * 初始化數據
     */
    private void loadData() {
        handlerThread = new HandlerThread("refreash");
        handlerThread.start();

        handler = new MyHandler(handlerThread.getLooper());
        handler.sendMessage(handler.obtainMessage());
    }

    /**
     * 子線程處理耗時操做
     */
    private void handleIntent() {
        try {
            //模擬耗時
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        size++;
        Message msg = uiHandler.obtainMessage();
        uiHandler.sendMessage(msg);
    }

    @Override
    protected void onDestroy() {
        handlerThread.quit();
        super.onDestroy();
    }
}複製代碼

該程序模擬實現以下功能:子線程執行一秒的耗時操做後,數值加1而且刷新界面,以下圖所示:oop

很明顯,你也能夠本身用Thread+Handler實現,只不過HandlerThread去作了封裝,IntentService中使用HandlerThread是比較經典的場景,後面會講解IntentService。post

4.源碼講解

/*
 * Copyright (C) 2006 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.os;

/**
 * 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 {
    int mPriority;
    int mTid = -1;
    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 overridden if needed to execute some
     * setup before Looper loops.
     */
    protected void onLooperPrepared() {
    }

    @Override
    public void run() {
        mTid = Process.myTid();
        Looper.prepare();
        synchronized (this) {
            mLooper = Looper.myLooper();
            notifyAll();
        }
        Process.setThreadPriority(mPriority);
        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;
    }

    /**
     * Quits the handler thread's looper. * <p> * Causes the handler thread's looper to terminate without processing any
     * more messages in the message queue.
     * </p><p>
     * Any attempt to post messages to the queue after the looper 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 because 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 looper looper has been asked to quit or false if the
     * thread had not yet started running.
     *
     * @see #quitSafely
     */
    public boolean quit() {
        Looper looper = getLooper();
        if (looper != null) {
            looper.quit();
            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 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 looper is 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 #getLooper} returns null), then false is returned.
     * Otherwise the looper is asked to quit and true is returned.
     * </p>
     *
     * @return True if the looper looper has been asked to quit or false if the
     * thread had not yet started running.
     */
    public boolean quitSafely() {
        Looper looper = getLooper();
        if (looper != null) {
            looper.quitSafely();
            return true;
        }
        return false;
    }

    /**
     * Returns the identifier of this thread. See Process.myTid().
     */
    public int getThreadId() {
        return mTid;
    }
}複製代碼

1)構造方法HandlerThread(String name) ;HandlerThread(String name,int priority) 傳入線程名和線程等級

2)當調用handlerThread.start()方法時,會調用HandlerThread的run()方法,該方法會建立looper對象,設置線程等級,循環looper。

3)當建立handler對象的時候,咱們會用HandlerThread的getLooper方法,該方法會返回Looper對象,可是有個wait(),何時喚醒呢,在HandlerThread的run()方法中會看到notifyAll()方法,就是等到looper建立完成,才能經過getLooper獲取到,這樣作是爲了解決這兩個線程的同步問題。

4)上面的例子代碼,在ondestory方法中,調用了handlerThread的quit()方法,quit方法中調用了looper的quit方法,把messageQueue中的message所有移除。若是咱們不調用quit()方法,子線程會一直處於等待狀態,全部須要手動調用quit方法。

------------------------------------------------------------------------------------------------

若有錯誤歡迎指出來,一塊兒學習。

相關文章
相關標籤/搜索