深入Android HandlerThread 使用及其源碼完全解析
關(guān)聯(lián)篇:深入Android的消息機制源碼詳解-Handler,MessageQueue與Looper關(guān)系
關(guān)聯(lián)篇:Handler內(nèi)存泄漏及其解決方案
本篇我們將來給大家介紹HandlerThread這個類,以前我們在使用線程執(zhí)行一個耗時任務(wù)時總會new一個Thread的線程去跑,當(dāng)任務(wù)執(zhí)行完后,線程就會自動被銷毀掉,如果又由新的任務(wù),我們又得新建線程.....我們假設(shè)這樣的一個情景,我們通過listview去加載圖文列表,當(dāng)我們往下滑動時,這時需要不斷去請求網(wǎng)絡(luò)資源,也就是需要不斷開線程去加載網(wǎng)絡(luò)資源,如果每次都new一個Thread,這顯然是不合理的,那么該怎么辦呢?相信大家都應(yīng)該用過圖片加載框架ImageLoader,其實ImageLoader內(nèi)部就是通過Handler+Looper+Thread來實現(xiàn)的,內(nèi)部維持一個線程池,通過Handler+Looper+Thread構(gòu)建循環(huán)線程,每次有任務(wù)就取出其中的任務(wù)放到線程池去執(zhí)行,沒有就一直處于等待狀態(tài),直到有新任務(wù)被投放進(jìn)來,如果任務(wù)過多就加入等待隊列,直到其中一個線程執(zhí)行完畢就從等待隊列獲取下一個執(zhí)行的任務(wù),這樣就可以避免過多創(chuàng)建Thread所造成的資源消耗。當(dāng)然Handler+Looper+Thread的實現(xiàn)方式并不是本篇的討論重點,我們要討論的是其實現(xiàn)替代者-HandlerThread,繼承自Thread,本質(zhì)是Thread,它與普通Thread的差別就在于,它有個Looper成員變量。其內(nèi)部就是通過Thread+Looper來實現(xiàn)的,說白了HandlerThread就是Android已經(jīng)封裝好的一個擁有自己looper的線程,我們可以利用它執(zhí)行一些耗時任務(wù)。我們先來看看HandlerThread的使用步驟并提供給大家一個使用案例:
一.HandlerThread的使用步驟
1.創(chuàng)建實例對象
HandlerThread handlerThread = new HandlerThread("downloadImage");
參數(shù)的作用主要是標(biāo)記當(dāng)前線程的名字,可以任意字符串。
2.啟動HandlerThread線程
//必須先開啟線程 handlerThread.start();
到此,我們就構(gòu)建完一個循環(huán)線程。那么我們怎么將一個耗時的異步任務(wù)投放到HandlerThread線程中去執(zhí)行呢?接下來看下面步驟:
3.構(gòu)建循環(huán)消息處理機制
/** * 該callback運行于子線程 */ class ChildCallback implements Handler.Callback { @Override public boolean handleMessage(Message msg) { //在子線程中進(jìn)行相應(yīng)的網(wǎng)絡(luò)請求 //通知主線程去更新UI mUIHandler.sendMessage(msg1); return false; } }
構(gòu)建異步handler
/** * 該callback運行于子線程 */ class ChildCallback implements Handler.Callback { @Override public boolean handleMessage(Message msg) { //在子線程中進(jìn)行相應(yīng)的網(wǎng)絡(luò)請求 //通知主線程去更新UI mUIHandler.sendMessage(msg1); return false; } }
第3步是構(gòu)建一個可以用于異步操作的handler,并將前面創(chuàng)建的HandlerThread的Looper對象和Callback接口類作為參數(shù)傳遞給當(dāng)前的handler,這樣當(dāng)前的異步handler就擁有了HandlerThread的Looper對象,而其中的handlerMessage方法來處理耗時任務(wù),Looper+Handler+MessageQueue+Thread異步循環(huán)機制構(gòu)建完成。下面我們來看一個使用案例
二.HandlerThread的使用案例
package com.zejian.handlerlooper; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.os.Message; import android.widget.ImageView; import com.zejian.handlerlooper.model.ImageModel; import com.zejian.handlerlooper.util.LogUtils; import java.io.BufferedInputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; /** * Created by zejian on 16/3/5. */ public class HandlerThreadActivity extends Activity { /** * 圖片地址集合,圖片來自網(wǎng)絡(luò). */ private String url[]={ "http://img.my.csdn.net/uploads/201407/26/1406383299_1976.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383291_6518.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383291_8239.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383290_9329.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383290_1042.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383275_3977.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383265_8550.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383264_3954.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383264_4787.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383264_8243.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383248_3693.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383243_5120.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383242_3127.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383242_9576.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383242_1721.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383219_5806.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383214_7794.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383213_4418.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383213_3557.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383210_8779.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383172_4577.jpg" }; private ImageView imageView; private Handler mUIHandler = new Handler(){ @Override public void handleMessage(Message msg) { LogUtils.e("次數(shù):"+msg.what); ImageModel model = (ImageModel) msg.obj; imageView.setImageBitmap(model.bitmap); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_handler_thread); imageView= (ImageView) findViewById(R.id.image); //創(chuàng)建異步HandlerThread HandlerThread handlerThread = new HandlerThread("downloadImage"); //必須先開啟線程 handlerThread.start(); //子線程Handler Handler childHandler = new Handler(handlerThread.getLooper(),new ChildCallback()); for(int i=0;i<10;i++){ //每個1秒去更新圖片 childHandler.sendEmptyMessageDelayed(i,1000*i); } } /** * 該callback運行于子線程 */ class ChildCallback implements Handler.Callback { @Override public boolean handleMessage(Message msg) { //在子線程中進(jìn)行網(wǎng)絡(luò)請求 Bitmap bitmap=downloadUrlBitmap(url[msg.what]); ImageModel imageModel=new ImageModel(); imageModel.bitmap=bitmap; imageModel.url=url[msg.what]; Message msg1 = new Message(); msg1.what = msg.what; msg1.obj =imageModel; //通知主線程去更新UI mUIHandler.sendMessage(msg1); return false; } } private Bitmap downloadUrlBitmap(String urlString) { HttpURLConnection urlConnection = null; BufferedInputStream in = null; Bitmap bitmap=null; try { final URL url = new URL(urlString); urlConnection = (HttpURLConnection) url.openConnection(); in = new BufferedInputStream(urlConnection.getInputStream(), 8 * 1024); bitmap=BitmapFactory.decodeStream(in); } catch (final IOException e) { e.printStackTrace(); } finally { if (urlConnection != null) { urlConnection.disconnect(); } try { if (in != null) { in.close(); } } catch (final IOException e) { e.printStackTrace(); } } return bitmap; } }
思路分析:在這個案例中,我們創(chuàng)建了兩個Handler,一個用于更新UI線程的mUIHandler和一個用于異步下載圖片的childHandler。最終的結(jié)果是childHandler會每個隔1秒鐘通過sendEmptyMessageDelayed方法去通知ChildCallback的回調(diào)函數(shù)handleMessage方法去下載圖片并告訴mUIHandler去更新UI界面。運行截圖如下:
到此,HandlerThread的基本使用我們都有所了解了,接下來我們掰掰HandlerThread源碼,挖挖其實現(xiàn)原理。
三.HandlerThread源碼解析
HandlerThread的源碼不多只有140多行,我們一步一步來分析,先來看看其構(gòu)造函數(shù):
/** * 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;//線程優(yōu)先級 int mTid = -1; Looper mLooper;//當(dāng)前線程持有的Looper對象 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() { }
從源碼可以很明顯的看出HandlerThread繼續(xù)自Thread,構(gòu)造函數(shù)也相當(dāng)簡單傳遞參數(shù)有兩個,一個是name指的是線程的名稱,一個是priority指的是線程優(yōu)先級,我們根據(jù)需要調(diào)用即可。成員變量mLooper就是HandlerThread自己持有的Looper對象。onLooperPrepared()該方法是一個空實現(xiàn),是留給我們必要時可以去重寫的,但是重寫時機是在Looper循環(huán)啟動前。還記得我們在前面創(chuàng)建完HandlerThread后還要去調(diào)用start()方法后才可以去創(chuàng)建Handler嗎?這是為什么呢?接下來我們就來揭曉其中奧秘:
@Override public void run() { mTid = Process.myTid(); Looper.prepare(); synchronized (this) { mLooper = Looper.myLooper(); notifyAll(); //喚醒等待線程 } Process.setThreadPriority(mPriority); onLooperPrepared(); Looper.loop(); mTid = -1; }
這個是HandlerThread的run方法,代碼也比較簡單,開始就通過Looper.prepare()去創(chuàng)建Looper對象,然后通過同步線程去給當(dāng)前成員變量mLooper賦值,并喚醒等待線程(后續(xù)會解析為什么要喚醒等待線程),然后在Looper.loop()循環(huán)啟動前調(diào)用了onLooperPrepared方法,到此Looper創(chuàng)建完成,循環(huán)線程也啟動完成。現(xiàn)在我們也就明白了創(chuàng)建HandlerThread后為什么要調(diào)用start方法了,因為通過調(diào)用start方法,程序會去執(zhí)行run方法,這樣才會去創(chuàng)建Looper對象并啟動Looper循環(huán),最后我們才能把Looper對象傳遞給Handler實例。
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; }
這個方法名一看就知道是獲取looper對象的,雖然很簡單,但是這里有個地方還是要說明一下,方法開始后先去判斷當(dāng)前線程是否是啟動狀態(tài),如果線程已經(jīng)啟動,再通過一個同步代碼塊去判斷當(dāng)前成員變量mLooper是否為空,如果為空,那就wait(),直到mLooper創(chuàng)建完成,否則就返回mLooper對象,那么為什么會由可能為空呢?還記得前面的Looper對象是在哪里創(chuàng)建的嗎?沒錯,是在子線程,這樣我們就無法保障我們在調(diào)用getLooper方法時Looper已經(jīng)創(chuàng)建完成。因此在前面的run方法中當(dāng)Looper創(chuàng)建完成后會調(diào)用notifyAll方法就是為了喚醒getLooper方法中的wait等待機制。
小結(jié):在獲取mLooper對象的時候存在一個同步的問題,只有當(dāng)線程創(chuàng)建成功并且Looper對象也創(chuàng)建成功之后才能獲得mLooper的值。這里等待方法wait和run方法中的notifyAll方法共同完成同步問題。
public boolean quit() { Looper looper = getLooper(); if (looper != null) { looper.quit(); return true; } return false; } public boolean quitSafely() { Looper looper = getLooper(); if (looper != null) { looper.quitSafely(); return true; } return false; }
最后就是兩個停止looper線程的方法了,以上有兩種讓當(dāng)前線程退出循環(huán)的方法的區(qū)別就是quitSafely方法效率比quit方法標(biāo)率低一點,但是安全。具體選擇哪種就要看大家需求了。到此,HandlerThread源碼就解析完了,相信大家對HandlerThread也有了比較全面的了解了,嗯,本篇結(jié)束。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android?RecyclerLineChart實現(xiàn)圖表繪制教程
這篇文章主要為大家介紹了Android?RecyclerLineChart實現(xiàn)圖表繪制教程,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12Android仿新浪微博oauth2.0授權(quán)界面實現(xiàn)代碼(2)
這篇文章主要為大家詳細(xì)介紹了Android仿新浪微博oauth2.0授權(quán)界面實現(xiàn)代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-11-11Android數(shù)據(jù)雙向綁定原理實現(xiàn)和應(yīng)用場景
本文介紹了Android數(shù)據(jù)雙向綁定的原理和實現(xiàn)方式,包括基于觀察者模式和數(shù)據(jù)綁定框架的實現(xiàn)方法,以及應(yīng)用場景和優(yōu)缺點的分析,幫助開發(fā)者了解和應(yīng)用數(shù)據(jù)雙向綁定技術(shù),提升應(yīng)用的交互性和響應(yīng)速度2023-04-04Android中利用App實現(xiàn)消息推送機制的代碼
Android中利用App實現(xiàn)消息推送機制的代碼,需要的朋友可以參考下。2011-05-05Android彈出dialog后無法捕捉back鍵的解決方法
這篇文章主要為大家詳細(xì)介紹了Android彈出dialog后無法捕捉back鍵的解決方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-09-09Android Jetpack 狠活Lifecycles與LiveData使用詳解
這篇文章主要為大家介紹了Android Jetpack 狠活Lifecycles與LiveData使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-10-10Android中GPS坐標(biāo)轉(zhuǎn)換為高德地圖坐標(biāo)詳解
最近因為公司需求,在做GPS定位,并且將獲得的坐標(biāo)顯示在高德地圖上,但是實際效果跟我們期望的是有偏差的。通過查閱資料,才知道有地球坐標(biāo)、火星坐標(biāo)之說。下面這篇文章就詳細(xì)介紹了Android中GPS坐標(biāo)轉(zhuǎn)換為高德地圖坐標(biāo)的方法,需要的朋友可以參考下。2017-01-01android教程之使用asynctask在后臺運行耗時任務(wù)
AsyncTask用在需要在ui線程中調(diào)用、在背景線程中執(zhí)行耗時任務(wù)、并且在ui線程中返回結(jié)果的場合。下面就是一個在背景中運行的AsyncTask的實現(xiàn)DownloadDBTask2014-02-02