android多線程之AsyncTask的初步認識(一)

來源:互聯網
上載者:User

之前,在學習多線程的時候,我首先學習了Handler的用法,瞭解了安卓中的通過使用Handler、Message、Looper、Thread來實現多線程操作的方法。

其實在安卓(Android 1.5)中提供了一個叫做AsyncTask的工具類,它使建立需要與使用者介面互動的長時間啟動並執行任務變得更簡單。從今天開始,我將學習AsyncTask的一些用法和原理。

首先看一下,在API中對AsyncTask的說明:

AsyncTaskenables proper and easy use of the UI thread. This class allows to performbackground operations and publish results on the UI thread without having tomanipulate threads and/or handlers.

AsyncTask is designed to be a helper class around Thread and Handler and does not constitute ageneric threading framework. AsyncTasks should ideally be used for shortoperations (a few seconds at the most.) If you need to keep threads running forlong periods of time, it is highly recommended you use the various APIsprovided by thejava.util.concurrent pacakge such as Executor, ThreadPoolExecutor and FutureTask.

我簡單翻譯一下:AsyncTask提供了對UI線程簡單應用的操作。這個類允許在不使用多線程和Handler的情況下,在後台執行操作並將結果反饋給UI線程。

AsyncTask被設計為Thread和Handler的協助類,它沒有構造通用的線程的架構(這句話不太理解,翻譯的不好)。對AsyncTasks合理的使用方法是用來進行短時間的操作(最多幾秒鐘)。如果你需要讓線程持續運行較長時間的話,強烈建議你去使用java.util.concurrent包中提供的其它API,比如Executor, ThreadPoolExecutor 和 FutureTask。

通過API中說明,我們對AsyncTask的作用和使用情境有了最基本的認識,但是,想要深入瞭解AsyncTask還是讓我們來看代碼吧


下面代碼實現的功能和我在學習Handler時是一樣的

點擊啟動按鈕,介面中出現一個進度條,並以每秒10%的進度增加,當增加到100%的時候,進度條消失。在這個過程中,我們也可以通過點擊取消按鈕來取消這個操作

下面是代碼


package com.example.asynctask1;import android.app.Activity;import android.os.AsyncTask;import android.os.Bundle;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.ProgressBar;public class MainActivity extends Activity {Button startButton = null;Button stopButton = null;ProgressBar progressbar = null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);startButton = (Button) findViewById(R.id.startButton);stopButton = (Button) findViewById(R.id.stopButton);progressbar = (ProgressBar) findViewById(R.id.progressBar);//為button綁定onclicklistenerstartButton.setOnClickListener(new ButtonOnclickListener());stopButton.setOnClickListener(new ButtonOnclickListener());}class ButtonOnclickListener implements OnClickListener{public void onClick(View v) {ProgressTask progressTask = new ProgressTask();switch(v.getId()){case R.id.startButton://啟動線程progressTask.execute(1);progressbar.setVisibility(View.VISIBLE);break;case R.id.stopButton://線程取消progressTask.cancel(true);progressbar.setVisibility(View.GONE);break;}}}class ProgressTask extends AsyncTask{protected String doInBackground(Integer... params) {int i = params[0];while(i<100){try {//控制線程延遲1秒Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}i += 10;//將更新內容發布到UI線程中,該方法會觸發onProgressUpdatepublishProgress(i);}return null;}//onProgressUpdate提供了可以更新UI的場所protected void onProgressUpdate(Integer... values) {Log.i("run", "run "+values[0]+"%");progressbar.setProgress(values[0]);if(values[0]>100)progressbar.setVisibility(View.GONE);}}}


比較前面使用Handler和Thread配合實現這個例子的代碼,我們發現,使用AsyncTask實現的代碼更加簡潔易懂。

在上面代碼中我們可以看到,要使用AsyncTask,我們首先要有一個繼承AsyncTask的子類,在子類中重載一些方法。

下面是今天學習的重點,AsyncTask的三個泛型型別和四個步驟

三個泛型型別:


class ProgressTask extends AsyncTask

AsyncTask定義了三種泛型型別Params,Progress和Result。

  • Params 啟動任務執行的輸入參數,比如HTTP請求的URL。
  • Progress 背景工作執行的百分比。
  • Result 後台執行任務最終返回的結果,比如String。

    四個步驟:

    我在代碼中重載了doInBackground、onProgressUpdate兩個方法,其實在非同步任務執行的時候,有四個步驟,對應四個方法:

    onPreExecute() 在UI線程上調用任務後立即執行。這步通常被用於設定任務,例如在使用者介面顯示一個進度條。doInBackground(Params...) 後台線程執行onPreExecute()完後立即調用,這步被用於執行較長時間的後台計算。非同步任務的參數也被傳到這步。計算的結果必須在這步返回,將傳回到上一步。在執行過程中可以調用publishProgress(Progress...)來更新任務的進度。onProgressUpdate(Progress...) 一次呼叫publishProgress(Progress...)後調用UI線程。執行時間是不確定的。這個方法用於當後台計算還在進行時在使用者介面顯示進度。例如:這個方法可以被用於一個進度條動畫或在文本域顯示記錄。onPostExecute(Result) 當後台計算結束時,調用UI線程。後台計算結果作為一個參數傳遞到這步。

    這四個方法不需要我們手動去調用,當非同步任務執行到相應步驟時,會自動調用這幾個方法,如果有需要,我們可以在聲明類的時候重載其中的方法。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.