Skip to content Skip to sidebar Skip to footer

Asynctask, Multiple Different Operations

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 diffe

Solution 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:

publicstaticfinalint FILE_TYPE = 0;
publicstaticfinalint INT_TYPE = 1;
publicstaticfinalint STRING_TYPE = 2;

taskargs = newObject[] { "mystring", new File("somefile.txt"), new myObject("somearg") };

new Task(STRING_TYPE, taskargs).execute();

AsyncTask

privateclassTaskextendsAsyncTask<URL, Integer, Long> {
    privateInttype;
    privateObject[] objects;
    publicTask(Inttype, Object[] objects) {
        this.type = type;
        this.objects = objects;
    }
    protectedLongdoInBackground(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 likeswitch (type) {
            case0:  taskFile();
                     break;
            case1:  taskInteger();
                     break;
            case2:  taskString();
                     break;
            default: break;
        }
        return totalSize;
    }

    protectedvoidonProgressUpdate(Integer... progress) {
        setProgressPercent(progress[0]);
    }

    protectedvoidonPostExecute(Long result) {
        showDialog("Downloaded " + result + " bytes");
    }
    protectedvoidtaskFile(){ //do something with objects array }protectedvoidtaskInteger(){ //do something with objects array }protectedvoidtaskString(){ //do something with objects array }
}

Post a Comment for "Asynctask, Multiple Different Operations"