我目前有一个有4种方法的课程。我需要将其更改为AsyncTask。每个方法都接收不同的参数(File,int,String ...)以使用post或get连接到不同的URL。我的问题是,我是否仍然可以在一个AsyncTask类中以某种方式拥有所有这些操作,或者我需要为每个方法创建新的AsyncTask类?
private class Task extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
答案 0 :(得分:1)
这取决于您是否需要同时运行所有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();
的AsyncTask
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 }
}