AsyncTask, multiple different operations

2019-09-04 07:48发布

I currently have one class with 4 methods. I need to change that to AsyncTask. Every method receives different parameters (File, int, String ...) to work with and connects to different URL with post or get. My question is can I still somehow have all those operations in one AsyncTask class or I will need to create new AsyncTask class for every method?

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");
 }
 }

1条回答
看我几分像从前
2楼-- · 2019-09-04 08:00

This depends if you need all 4 AsyncTasks to run simultaneously or if they can run sequentially.

I would imagine they can run sequentially since that's how they are running currently in the Main thread, so just pass all the needed parameters and execute their operations one by one. In fact, if the functions are already written, just move those functions into your AsyncTask class:

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 }
}
查看更多
登录 后发表回答