我AsyncTask
用来下载一些文件,并想在所有任务完成后做一些事情。
有什么简单的方法可以做到这一点?
跟踪您正在运行的异步任务数量,并在总数为 0 时执行某些操作。
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
public int numOfTasks = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void addTask(){
numOfTasks++;
}
public void removeTask(){
numOfTasks--;
}
public void allTasksComplete(){
if(numOfTasks ==0){
//do what you want to do if all tasks are finished
}
}
class RequestTask extends AsyncTask<String, String, String>{
@Override
protected String doInBackground(String... uri) {
String responseString = "";
return responseString;
}
@Override
protected void onPreExecute()
{
addTask(); // adds one to task count.
super.onPreExecute();
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
removeTask(); // subtracts one from task count.
allTasksComplete(); // checks to see if all tasks are done... task count is 0
}
}
}
AsyncTask 有一个回调方法名onPostExecute
。后台任务完成后执行。
当 Asyn 任务完成后台处理时,您可以使用 onPostExecute() 回调,在典型的场景中,您会通知 UI(列表适配器或 UI 活动)文件下载完成并且 UI 可以刷新或填充数据。
onPreExecute(),在任务执行后立即在 UI 线程上调用。此步骤通常用于设置任务,例如通过在用户界面中显示进度条。
请看一下这个 Android Ref 示例:
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));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
http://developer.android.com/reference/android/os/AsyncTask.html
示例 2: