AsyncTask is designed to be a helper class around
Thread
and Handler
and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent
pacakge such as Executor
, ThreadPoolExecutor
and FutureTask
.ref: 老灰鴨的筆記本
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> { // 對照前面提到的 3 個傳入的參數 // URL 指 Params 參數的類別 // Integer 指 Progress 參數的類別 // Long 指 Result 參數的類別 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() 以更新 UI 畫面, // 可藉由此方式更新畫面上的進度表 publishProgress((int) ((i / (float) count) * 100)); // Escape early if cancel() is called if (isCancelled()) break; } // 將 totalSize 傳給 onPostExecute() return totalSize; } protected void onProgressUpdate(Integer... progress) { // 這裡接收傳入的 progress 值, 並更新進度表畫面 // 參數為 Integer 型態的陣列 // 但因為在 doInBackground() 只傳一個參數 // 所以以 progress[0] 取得傳入參數 setProgressPercent(progress[0]); } protected void onPostExecute(Long result) { showDialog("Downloaded " + result + " bytes"); } }
ref: 老灰鴨的筆記本
AsyncTask
沒有留言:
張貼留言