Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

publishProgress from inside a function in doInBackground?

Tags:

android

I use an AsyncTask to perform a long process.

I don't want to place my long process code directly inside doInBackground. Instead my long process code is located in another class, that I call in doInBackground.

I would like to be able to call publishProgress from inside the longProcess function. In C++ I would pass a callback pointer to publishProgress to my longProcess function.

How do I do that in java ?

EDIT:

My long process code:

public class MyLongProcessClass
    {
    public static void mylongProcess(File filetoRead)
        {
        // some code...
        // here I would like to call publishProgress
        // some code...
        }
    }

My AsyncTask code:

private class ReadFileTask extends AsyncTask<File, Void, Boolean>
    {
    ProgressDialog  taskProgress;

    @Override
    protected Boolean doInBackground(File... configFile)
        {
        MyLongProcessClass.mylongProcess(configFile[0]);
        return true;
        }
    }

EDIT #2 The long process method could also be non-static and called like this:

MyLongProcessClass fileReader = new MyLongProcessClass();
fileReader.mylongProcess(configFile[0]);

But that does not change my problem.

like image 252
Regis St-Gelais Avatar asked Apr 01 '11 18:04

Regis St-Gelais


People also ask

Is it possible to start AsyncTask from background thread?

To start an AsyncTask the following snippet must be present in the MainActivity class : MyTask myTask = new MyTask(); myTask. execute(); In the above snippet we've used a sample classname that extends AsyncTask and execute method is used to start the background thread.

How many methods are compulsory to override when we are working in AsyncTask?

AsyncTask must be subclassed to be used. The subclass will override at least one method ( doInBackground(Params...) ), and most often will override a second one ( onPostExecute(Result) .)

Which method is called by the doInBackground () to publish updates on the user interface thread?

onProgressUpdate – called on the UI thread by Android whenever publishProgress(Progress…) is called (typically in the doInBackground method) to provide the user interface (and user) with updates while the separate thread is still running.

Which methods are run on the main UI thread AsyncTask?

onPreExecute: This is the first method that runs when an asyncTask is executed. After this, doInBackground is executed. This method runs on the UI thread and is mainly used for instantiating the UI.


4 Answers

The difficulty is that publishProgress is protected final so even if you pass this into your static method call you still can't call publishProgress directly.

I've not tried this myself, but how about:

public class LongOperation extends AsyncTask<String, Integer, String> {
    ...

    @Override
    protected String doInBackground(String... params) {
        SomeClass.doStuff(this);
        return null;
    }
    ...

    public void doProgress(int value){
        publishProgress(value);
    }
}
...
public class SomeClass {
    public static void doStuff(LongOperation task){
        // do stuff
        task.doProgress(1);
        // more stuff etc
    }
}

If this works please let me know! Note that calling doProgress from anywhere other than a method that has been invoked from doInBackground will almost certainly cause an error.

Feels pretty dirty to me, anyone else have a better way?

like image 89
dave.c Avatar answered Oct 23 '22 20:10

dave.c


A solution could be placing a simple public class inside the AsyncTask (make sure the task you define is also public) which has a public method that calls publishProgress(val). Passing that class should be available from any other package or class.

public abstract class MyClass {

    public MyClass() {
        // code...
    }

    // more code from your class...

    public class Task extends AsyncTask<String, Integer, Integer> {
        private Progress progress;

        protected Task() {
            this.progress = new Progress(this);
        }

        // ...

        @Override
        protected Integer doInBackground(String... params) {
            // ...
            SomeClass.doStuff(progress);
            // ...
        }

        // ...

        @Override
        protected void onProgressUpdate(Integer... progress) {
            // your code to update progress
        }

        public class Progress {
            private Task task;

            public Progress(Task task) {
                this.task = task;
            }

            public void publish(int val) {
                task.publishProgress(val);
            }
        }
    }
}

and then in the other class:

public class SomeClass {
    public static void doStuff(Progress progress){
        // do stuff
        progress.publish(20);
        // more stuff etc
    }
}

This worked for me.

like image 5
jalv1039 Avatar answered Oct 23 '22 19:10

jalv1039


Split up the longProcess() function into smaller functions.

Sample code:

@Override
protected Boolean doInBackground(Void... params) {
    YourClass.yourStaticMethodOne();
    publishProgress(1);
    YourClass.yourStaticMethodTwo();
    publishProgress(2);
    YourClass.yourStaticMethodThree();
    publishProgress(3);

    // And so on...
    return true;
}
like image 2
Wroclai Avatar answered Oct 23 '22 18:10

Wroclai


If this works please let me know! Note that calling doProgress from anywhere other than a method that has been invoked from doInBackground will almost certainly cause an error.

Yes, it works. I extended it so that you don't need to pass the AsyncTask as a parameter to your method. This is particularly useful if (like me) you've already written all your methods before deciding that actually you do need to publish some progress, or in my case, update the UI from an AsyncTask:

public abstract class ModifiedAsyncTask<A,B,C> extends AsyncTask<A,B,C>{

    private static final HashMap<Thread,ModifiedAsyncTask<?,?,?>> threads 
             = new HashMap<Thread,ModifiedAsyncTask<?,?,?>>();

    @Override
    protected C doInBackground(A... params) {
        threads.put(Thread.currentThread(), this);
        return null;        
    }

    public static <T> void publishProgressCustom(T... t) throws ClassCastException{
        ModifiedAsyncTask<?, T, ?> task = null;
        try{
            task = (ModifiedAsyncTask<?, T, ?>) threads.get(Thread.currentThread());
        }catch(ClassCastException e){
            throw e;
        }
        if(task!=null)
            task.publishProgress(t);
    }
}

public class testThreadsActivity extends Activity {

/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);        
    }

    public void Button1Clicked(View v){
        MyThread mthread = new MyThread();
        mthread.execute((Void[])null);      
    }

    private class MyThread extends ModifiedAsyncTask<Void, Long, Void>{

        @Override
        protected Void doInBackground(Void... params) {
            super.doInBackground(params);

            while(true){
                myMethod(System.currentTimeMillis());               
                try {
                    Thread.sleep(1000L);
                } catch (InterruptedException e) {                  
                    return null;
                }
            }           
        }

        protected void onProgressUpdate(Long... progress) {
            //Update UI
            ((TextView) findViewById(R.id.textView2)).setText("The Time is:" + progress[0]);
        }


    }

    private void myMethod(long l){

        // do something

        // request UI update
        ModifiedAsyncTask.publishProgressCustom(new Long[]{l});
    }

}

Feels pretty dirty to me, anyone else have a better way?

My way is probably worse. I'm calling a static method for doProgress (which I called publishProgressCustom). It can be called from anywhere without producing an error (as if the thread has no corresponding AsyncTask in the hashMap, it won't call publishProgress). The down side is that you have to add the Thread-AsyncTask mapping yourself after the thread has started. (You can't override AsyncTask.execute() sadly as this is final). I've done it here by overriding doInBackground() in the super class, so that anyone extending it just has to put super.doInBackground() as the first line in their own doInBackground().

I don't know enough about Threads and AsyncTask to know what happens to the HashMap references once the Thread and/or AsyncTask comes to an end. I suspect bad things happen, so I wouldn't suggest anyone try my solution as part of their own unless they know better

like image 1
James Coote Avatar answered Oct 23 '22 20:10

James Coote