AsyncTask, multiple different operations

给你一囗甜甜゛ 提交于 2019-12-13 08:24:11

问题


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:


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 }
}


来源:https://stackoverflow.com/questions/13828359/asynctask-multiple-different-operations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!