这取决于您是否需要所有 4 个 AsyncTasks 同时运行或者它们是否可以按顺序运行。
我想它们可以按顺序运行,因为它们当前在主线程中是这样运行的,所以只需传递所有需要的参数并一一执行它们的操作。事实上,如果函数已经编写好了,只需将这些函数移动到您的 AsyncTask 类中:
MainActivity.java:
public static final int FILE_TYPE = 0;
public static final int INT_TYPE = 1;
public static final int STRING_TYPE = 2;
taskargs = new Object[] { "mystring", new File("somefile.txt"), new myObject("somearg") };
new Task(STRING_TYPE, taskargs).execute();
异步任务
private class Task extends AsyncTask<URL, Integer, Long> {
private Int type;
private Object[] objects;
public Task(Int type, Object[] objects) {
this.type = type;
this.objects = objects;
}
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
}
//obviously you can switch on whatever string/int you'd like
switch (type) {
case 0: taskFile();
break;
case 1: taskInteger();
break;
case 2: taskString();
break;
default: break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
protected void taskFile(){ //do something with objects array }
protected void taskInteger(){ //do something with objects array }
protected void taskString(){ //do something with objects array }
}