0

我目前有一堂课有 4 种方法。我需要将其更改为 AsyncTask。每个方法都接收不同的参数(文件、整数、字符串...)以使用并使用 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");
 }
 }
4

1 回答 1

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();

异步任务

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 }
}
于 2012-12-11T21:04:41.570 回答