Android異步任務庫:android-multithread

jopen 10年前發布 | 17K 次閱讀 Android Android開發 移動開發

android-multithread 是一個android平臺上的 擴展任務庫,在AsyncTask基礎上進行擴展。

主要特性如下:

1、擴展自AsyncTask,隨系統升級

2、增加里任務監聽TaskListener,可以有效地將UI和邏輯分開;

3、任務監聽TaskListener的所有回調函數內,可以直接進行UI操作。

4、可以設置線程池


用法

1.繼承 com.github.snowdream.android.util.concurrent.AsyncTask

//inherit a class from com.github.snowdream.android.util.concurrent.AsyncTask
public class DownloadFilesTask extends AsyncTask {
 public DownloadFilesTask(TaskListener listener) {
      //explicit inherit the construction from the super class.
      super(listener);
 }


/**
 * TODO 
 * if error occurs,carry it out.
 * 
 * if (listener != null) {
 *    listener.onError(new Throwable());
 * }
 */
protected Long doInBackground(URL... urls) {
     int count = urls.length;
     long totalSize = 0;
     for (int i = 0; i < count; i++) {
         totalSize += 10;
         publishProgress((int) ((i / (float) count) * 100));
         // Escape early if cancel() is called
         if (isCancelled()) break;
         try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
     }
     return totalSize;
 }
}



2.定義一個 TaskListener.其中的第一個泛型參數是返回結果類型,第二個泛型參數是任務進度的類型。

private TaskListener listener = new TaskListener(){


    @Override
    public void onStart() {
        super.onStart();
        Log.i("onStart()");
    }


    @Override
    public void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        Log.i("onProgressUpdate(values)" + values[0] );
    }


    @Override
    public void onSuccess(Long result) {
        super.onSuccess(result);
        Log.i("onSuccess(result)" + result);
    }


    @Override
    public void onCancelled() {
        super.onCancelled();
        Log.i("onCancelled()");
    }


    @Override
    public void onError(Throwable thr) {
        super.onError(thr);
        Log.i("onError()");
    }


    @Override
    public void onFinish() {
        super.onFinish();
        Log.i("onFinish()");
    }


};


3.創建一個AsyncTask任務,并且執行。

URL url = null;
try {
    url = new URL("http://www.baidu.com/");
} catch (MalformedURLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}


new DownloadFilesTask(listener).execute(url,url,url);

項目主頁:http://www.baiduhome.net/lib/view/home/1389228911843

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!