之前,在學習多線程的時候,我首先學習了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。