android耗時任務_HandlerThread

來源:互聯網
上載者:User

標籤: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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.