我正在使用AsyncTask
下载某些文件,并希望在完成所有任务后执行某些操作。
有没有简单的方法可以做到这一点?
答案 0 :(得分:4)
跟踪已运行的异步任务的数量,并在总数为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
}
}
}
答案 1 :(得分:0)
AsyncTask有一个回调方法名onPostExecute
。它将在后台任务完成时执行。
答案 2 :(得分:0)
当Asyn任务完成后台处理时,您可以使用onPostExecute()回调,在典型的情况下,您将通知UI(列表适配器或UI活动)文件的下载已完成,UI可以刷新或填充数据。 / p>
onPreExecute(),在执行任务后立即在UI线程上调用。此步骤通常用于设置任务,例如通过在用户界面中显示进度条。
请查看此Android参考示例:
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: