Generic Asynctask For Ws Calls In Android
Solution 1:
In Java, you cannot pass a method as a parameter, but you can pass an object that extends or implements an ancestor and overrides that method. The Command pattern uses this concept (http://en.wikipedia.org/wiki/Command_pattern).
Here's an idea of the approach:
privatestaticinterfaceCommand {
publicvoidexecute();
}
publicstatic final classMyWsCommand1implementsCommand {
@Overridepublicvoidexecute() {
// TODO your WS code 1
}
}
publicstatic final classMyWsCommand2implementsCommand {
@Overridepublicvoidexecute() {
// TODO your WS code 2
}
}
privatestaticclassGenericAsyncTask<Params, Progress, Result> extendsAsyncTask<Params, Progress, Result> {
privateCommand command;
publicGenericAsyncTask(Command command) {
super();
this.command = command;
}
@OverrideprotectedResultdoInBackground(Params... params) {
// TODO your code
command.execute();
// TODO your codereturnnull;
}
}
privateGenericAsyncTask<Object, Object, Object> myAsyncTask1;
privateGenericAsyncTask<Object, Object, Object> myAsyncTask2;
And use those in your code:
myAsyncTask1 = newGenericAsyncTask<Object, Object, Object>(newMyWsCommand1());
myAsyncTask1.execute();
...
myAsyncTask2 = newGenericAsyncTask<Object, Object, Object>(newMyWsCommand2());
myAsyncTask2.execute();
Solution 2:
by WS , you mean webservice?
asyncTask is not meant to be used for such long tasks . they are supposed to do small tasks . things that take (approx.) less than 5 seconds .
if you wish to do very long tasks , use a simple thread and consider putting it in a service.
also , in order to communicate with it , you can communicate with the service , and when you need to post something to the UI thread , use a handler .
Solution 3:
The most close answer is this
You can choose the method in the same UI which waits until the background process ends
Solution 4:
I would use Async, and I did on a production implementation. The issue you'll run into is doing more logic in the doInBackground because if you watch your debug build any time you see it say "Skipped X Frames" you may want to do a lot of post processing in doInBackground still.
Using an interface is the best approach, it's how I implemented my Async class. full.stack.ex hit the nail on the head with that answer. That answer shows a clear, simple, powerful way to extend Async and use it for your purpose.
Post a Comment for "Generic Asynctask For Ws Calls In Android"