標籤:android 耗時任務 looper handler anr
HandlerThread 在上一篇android耗時任務_handler中介紹了handler的運作機制,並且介紹了一個普通線程中產生looper並使用handler機制通訊的簡單例子。我們知道在普通線程中是沒有looper的,也就不好在普通線程空間中使用handler機制,如果每次都像上一篇的例子那樣做的話就會略顯麻煩。其實Android已經封裝了一個擁有自己looper的線程HandlerThread,它的實現和上一篇中給出的例子基本一,只是更加專業一點。下面是此類的詳細代碼。
public class HandlerThread extends Thread { private int mPriority; private int mTid =-1; private Looper mLooper; publicHandlerThread(String name) { super(name); mPriority =Process.THREAD_PRIORITY_DEFAULT; } publicHandlerThread(String name, int priority) { super(name); mPriority =priority; } protected void onLooperPrepared() { } public void run() { mTid =Process.myTid(); Looper.prepare(); synchronized(this) { mLooper =Looper.myLooper(); notifyAll(); } Process.setThreadPriority(mPriority); onLooperPrepared(); Looper.loop(); mTid = -1; } public Looper getLooper() { if (!isAlive()) { return null; } // If the threadhas been started, wait until the looper has been created. synchronized(this) { while(isAlive() && mLooper == null) { try { wait(); } catch(InterruptedException e) { } } } return mLooper; } public boolean quit(){ Looper looper =getLooper(); if (looper !=null) { looper.quit(); return true; } return false; } public intgetThreadId() { return mTid; }}此類就是繼承了Thread類,使用此類時一定要注意必須start(),否則run()方法沒有調用,handler機制也就沒有建立起來。
經典應用對於HandlerThread的一個經典應用就是在service中的應用,我們知道,一般而言service是運行在主線程中的,在android耗時任務_ANR中我也建議在BroadcastReceiver中啟動service,在service中啟動線程處理耗時任務。那麼如何啟動線程,下面給出一個經典的代碼:
public class BackService extends Service {private ServiceHandler serviceHandler;@Overridepublic IBinder onBind(Intent arg0) {return null;}private final class ServiceHandler extends Handler {public ServiceHandler(Looper looper) {super(looper);}@Overridepublic void handleMessage(Message msg) {super.handleMessage(msg);onHandleIntent((Intent) msg.obj);// 在其參數startId跟最後啟動該service時產生的ID相等時才會執行停止服務。stopSelf(msg.arg1);}}@Overridepublic void onCreate() {super.onCreate();HandlerThread thread = new HandlerThread("BackService");thread.start();Looper serviceLooper = thread.getLooper();serviceHandler = new ServiceHandler(serviceLooper);}@Overridepublic void onStart(Intent intent, int startId) {Message msg = serviceHandler.obtainMessage();msg.arg1 = startId;msg.obj = intent;serviceHandler.sendMessage(msg);}protected void onHandleIntent(Intent intent) { //做你的非同步任務}}
android耗時任務_HandlerThread