編輯:關於 Android 程式設計
先前介紹了 Handler 與 Thread,接下來要談的是 AsyncTask——它其實是兩者封裝後的產物,讓開發更為便利。使用 AsyncTask 時有一點非常重要:務必仔細閱讀 API 文件,因為它有若干必須遵守的使用限制,下文將重點說明。
AsyncTask 是 Android 提供的一個簡單、輕量級的多執行緒類別,讓我們能容易地建立背景執行緒執行耗時操作,並在過程中更新 UI。之所以稱其「輕量級」,是因為相較直接使用 Thread 缺少了部分靈活性。它能在背景執行運算、於 UI 執行緒發布結果,而無需手動操作執行緒或 Handler。
AsyncTask 的定位是作為 Thread 與 Handler 的輔助類,並非通用的執行緒框架,適合執行「短作業」(最長數秒)。若需長時間保持執行緒運行,強烈建議改用 java.util.concurrent 套件中的 Executor、ThreadPoolExecutor 與 ThreadPoolExecutor 相關的 FutureTask 等類別。
一個 AsyncTask 由三部分泛型與四個步驟組成:三種參數類型 Params、Progress、Result,以及四個步驟 onPreExecute、doInBackground、onProgressUpdate、onPostExecute。
AsyncTask 為抽象類,必須建立子類繼承它才能使用。子類至少要覆寫 doInBackground(Params...),通常也會覆寫 onPostExecute(Result)。以下為官方範例:
[java]
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
if (isCancelled()) break; // 若呼叫 cancel() 則提早結束
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
建立完成後,執行任務非常簡單:
[java]
new DownloadFilesTask().execute(url1, url2, url3);
AsyncTask 定義了三種泛型:Params(啟動任務的輸入參數,如 HTTP 請求的 URL)、Progress(背景任務的執行百分比)、Result(背景任務最終返回的結果,如 String、Integer)。
其執行分為四個步驟,每步對應一個回呼方法:
onPreExecute():在執行實際背景操作前,由 UI 執行緒呼叫,可做前置準備,例如顯示進度條。此可不實作。doInBackground(Params...):在 onPreExecute 之後執行,運行於背景執行緒,負責耗時的處理工作;可呼叫 publishProgress() 更新即時進度。此為抽象方法,子類必須實作。onProgressUpdate(Progress...):publishProgress() 被呼叫後,由 UI 執行緒呼叫,用以在介面展示任務進展。onPostExecute(Result):doInBackground 完成後由 UI 執行緒呼叫,將背景計算結果回傳並展示給使用者。onCancelled():使用者取消任務時呼叫。execute() 必須在 UI 執行緒中呼叫。此外,doInBackground 與 onPostExecute 的參數必須對應——它們在 AsyncTask 宣告的泛型參數列表中指定:第一個為 doInBackground 接受的參數、第二個為顯示進度的參數、第三個為 doInBackground 回傳並傳給 onPostExecute 的參數。閱讀原始碼可知,AsyncTask 是利用 java.util.concurrent 框架來管理執行緒與任務執行的。
[java]
public class Asy1Activity extends Activity {
Button download;
ProgressBar pb;
TextView tv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.asy1);
pb = (ProgressBar) findViewById(R.id.pb);
tv = (TextView) findViewById(R.id.tv);
download = (Button) findViewById(R.id.download);
download.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new DownloadTask().execute(100);
}
});
}
class DownloadTask extends AsyncTask<Integer, Integer, String> {
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
tv.setText(values[0] + "%");
}
@Override
protected void onPostExecute(String result) {
setTitle(result);
super.onPostExecute(result);
}
@Override
protected String doInBackground(Integer... params) {
for (int i = 0; i <= 100; i++) {
pb.setProgress(i);
publishProgress(i);
try {
Thread.sleep(params[0]);
} catch (InterruptedException e) {
e.printStackTrace();
}
}\n return "執行完畢";
}
}
}
以下範例示範用 AsyncTask 從網路下載圖片,並在下載過程中透過 ProgressBar 顯示進度:
[java]
class AsyncTaskLoadImage extends AsyncTask<String, Integer, Bitmap> {
@Override
protected Bitmap doInBackground(String... params) {
Bitmap bitmap = null;
try {
URL url = new URL(params[0]);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
int MAX = urlConnection.getContentLength();
progressBar.setMax(MAX);
InputStream inputStream = urlConnection.getInputStream();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int len = 0;
int processBarNum = 0;
while ((len = inputStream.read(b)) != -1) {
byteArrayOutputStream.write(b, 0, len);
processBarNum += len;
publishProgress(processBarNum);
}\n bitmap = BitmapFactory.decodeByteArray(byteArrayOutputStream.toByteArray(), 0, MAX);
inputStream.close();
} catch (MalformedURLException e) {\br />
e.printStackTrace();
} catch (IOException e) {\br />
e.printStackTrace();
}\n return bitmap;
}
@Override
protected void onProgressUpdate(Integer... values) {
progressBar.setProgress(values[0]);
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
super.onPostExecute(result);
}
}
透過 execute(imageUrl) 啟動任務後,doInBackground 會在背景下載圖片並回報進度,onProgressUpdate 更新進度條,最後 onPostExecute 將圖片設定到 ImageView 上顯示,即可完成一個流暢且不阻塞 UI 的網路圖片下載功能。
微信第三方登入 Android 端實作解析
微信第三方登入讓使用者能快速進入 App,也減少重複註冊的成本。在 Android 端實作時,重點是取得授權碼,再交由伺服器完成後續驗證。 前置準備 首先需要在微信開放平
用 GLSL 實作輝光(Glare / Glow)效果:原理、流程與 Shader
引言 GraphicsLab Project 立項之後,大部分時間都花在搭 Shader 實驗環境上。環境終於堪用,於是就拿它來做第一個實際效果——輝光。本文記錄在 Op
自定義 ViewGroup 打造微信朋友圈九宮格
本文以自定義 ViewGroup 實作類似微信朋友圈的九宮格圖片展示效果。相較於單純使用 GridView,自定義 ViewGroup 能更靈活地控制列數、每列數量、單圖
Android 定時器的三種實作方式完整比較
在 Android 開發中,定時反覆執行某項任務是很常見的需求。本文整理了實作定時器的三種經典寫法,並附上完整範例供參考。 先來看看運行效果: 由於三種做法都相當簡潔,