Search code examples
androidandroid-asynctaskcommand-pattern

Android: AsyncTask using Command pattern ... How Can I publish the progress?


I would like a more generic and easier approach for starting methods in the background. So the Command pattern looks like a good candidate.

@Full stack ex describes an implementation of the Command pattern in his post with AsyncTask .

The problem is : how can I publish the progress in my method, executing in the background, via the normal AsyncTask Progressdialog or callback?

Normally we use publishProgress( progress) ... but that is not possible. publishProgress is of scope 'protected'. Calling directly onProgressUpdate( ) updating the dialog is of course not possible, crossing the line of background process and UI process.

How can I use this or similar approach AND publish progress (via

private static interface Command {
    public void execute();
}
public static final class MyWsCommand1 implements Command {
    @Override
    public void execute() {
        // ------- TODO YOUR CODE ---------
        publishProgress( 90); // similar to this
    }
}
private static class GenericAsyncTask<Params, Progress, Result> extends AsyncTask<Params, Progress, Result> {    
    private Command command;    
    public GenericAsyncTask(Command command) {
        super();
        this.command = command;
    }
    @Override
    protected Result doInBackground(Params... params) {
        command.execute(); 
        return null;
    }
}
private GenericAsyncTask<Object, Object, Object> myAsyncTask1;
myAsyncTask1 = new GenericAsyncTask<Object, Object, Object>(new MyWsCommand1());
myAsyncTask1.execute();

Solution

  • publishProgress is of scope 'protected'

    That means you can call it from a child class. A protected field or method can be accessed in the class itself, and any class that inherits from it. Your original plan should work.