Android: How to handle multiple tasks - android

I want to perform multiple tasks in Android. I know I can use AsyncTask for this. But my requirement is I want to execute second task only completion of first task. Then will execute the third task only after completion of second task. How it could be possible.
For this I am thinking to use multiple AsyncTasks i mean inside doInBackground of first AsynTask I want to start second AsyncTask. Similarly inside doInBackground of secondAsynTask I want to start third AsyncTask and so on.... Is it ok if I implement like this with out any performance issue or is there any other way of doing this. Please share your thoughts on this.

Create multiple AsyncTasks and call them in a chain.
E.g.:
Call the first task:
new FirstTask().execute();
Then FirstTask class overrides onPostExecute where it calls the second class:
new SecondTask().execute()
and so on.

If you don't want to reinvent the wheel you could use concat () operator of rxjava.
https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators#concat

Related

Get data from more than one AsyncTask in one class?

My situation is this:
first I call first AsyncTask which fetched required Items from database. After that, I call another AsyncTask, which fetches these Item images.
I am getting data from AsynTasks by using callback.
Here is the issue - since I am using callback, in my class I have method processFinish which returns AsyncTask data when it finishes its computation. The problem is with two Async tasks which depend on each other. What should I do now?
You can use the get() method of asyncTask that will wait for the output and wont proceed further
also you can use it with a timeout.
ex new BackgroundTask().execute.get();
or
new BackgroundTask.execute.get(long timeout);
You could execute one AsyncTask inside another, but you should do it inside onPostExecute() because this method runs on the UI thread.
#Override
protected void onPostExecute(Void args) {
new AsyncTask2.execute(..); // Start second task once you've got first results
}
And you call your method processFinish(..) only once, after the second AsyncTask is completed.
Anyway, is there a reason why you use two AsyncTasks ? With your explanations we could believe that you might be able to use only one task.

AsyncTask called a lot from many places

I'm using a simple AsyncTask to download the sourcecode of a web page as a String. So far everything works fine.
However, I don't want to always do the same thing with the result String, sometimes I want to fill the gui with it, sometimes I want to parse it, sometimes I want to call more functions with it as a parameter.
Actually, I have more than one activity and more than one class that need to download the sourcecode of a page.
Of course, onPostExecute() is what has to handle the result of my Task, but since it will be called from so many places and for so many different reasons I'm really at a loss.
What can I do?
I really don't want to write 20 AsyncTasks that always do the same thing in their doInBackground(...) with different onPostExecute, nor I want the code from 20 different classes/activity to end up in a single onPostExecute, my code would be so complicated to maintain.
Any suggestion?
Thanks
I would resolve it with the use of interfaces. Make an async task that does the right stuff in the doInBackground and that takes some parameter so that you know what to do in the onPostExecute and pass the parameter and result down to onPostExecute.
then make an interface with a method like handleSourceCodeString(String source); and then implement one class for every action that you want to do. Then put the classes in a map in some init function.
Map<String, Class> myActionMap = new HashMap<String,Class>;
myActionMap.put("parse-soruce", ParseSource.class) //(where ParseSource.class implements your interface)
and then in your postExecute do something like:
((MyActionInterface)myActionMap.get(action).newInstance()).handleSourceCodeString(source);
I found this... love the idea... seems pretty straight forward and better than using interfaces in my opinion.
AsyncTask onPostExecute call from outside the AsyncTask
Look at the first answer

How to run a function with different parameters parallely in android?

I have a function called computeStrokes and I need to call it twice with different parameters.. There is a method in Asynctask called executeOnExecutor which allows a asynctask to run two threads parallely.I was not able to understand how to call this function twice within the doInBackground method of the AsyncTask.
Can Someone just help me with the code of this section i.e doInBackground
If you really need run 2 tasks in parallel from an AsyncTask then you can probably start 2 tasks in doInBackground and wait in there for the completion of both. This can be achieved with the help of Executors and a Future

Android AsyncTask inside AsyncTask

So, I'm working on a barcode decoder, which once we have the barcode goes to multiples API over the internet to decode what was just scanned.
The thing is that I have to link some XML parsing together, and I don't know if I'm doing it right.
So, once the barcode is scanned, my program calls an ASyncTask which goes over an API to retrieve the product name. Once it has the name, I want it to call another ASyncTask. I know this is possible by instantiating an ASyncTaks in the onPostExecute() of the other but, I think this is wrong, because it's like boxes within boxes.
So isn't it possible/better to instantiate my second ASyncTask inside my main Activity, and make it wait until my first ASyncTask is finished ?
(english isn't my primary language, I hope I made myself clear).
I think it's absolutely legitimate to start the second AsyncTask in the onPostExecute of the first AsyncTask, Mixing both operations is a bad logical idea, As "The Offspring" said - "You've gotta keep 'em separated"
If you don't want it to be directly inside the onPostExecute itself, set a handler to execute it in the activity and call this handler from onPostExecute.
And last thing - If you have a lot of logic - move it to a separate file, don't keep it all at the same file.
In situations like this it might be better to batch long running operations together in one AsyncTask.
Another option is to use the Loaders API, this makes chaining tasks much easier http://developer.android.com/guide/topics/fundamentals/loaders.html
You can go for another approach if you are facing often a situation like this. That is to merge requests and operations inside of runnables/callables and to manage them separately within say a queue for instance.
Here is a nice approach.
http://ugiagonzalez.com/2012/07/02/theres-life-after-asynctasks-in-android/

some kind of queue for asynctask

Hello
I have ListView with list of files. i click item and start to download this file in asynctask.
then i click another one and it must be put in queue, wait for that file and start ot download after it finishes. i can make some class that will hold all clicked links, and pass it to asynctask downloading part? and than somehow process them. but want to know is it the right way?
any links of sugestions? thanks
If you're set on using AsyncTask then, yeah, hold your clicked links and kick off new tasks when appropriate. You should note that AsyncTask is like the 'pocket knife' for threading in Android apps.
If you really need to manage a bunch of background tasks, and it sounds like you do, take a look at ThreadPoolExecutor. You get a lot of flexibility.
BlockingQueue
ThreadPoolExecutor
More Info
Example
Take a look at HandlerThread and the Handler class. You need one handler to pass tasks to the background HandlerThread and another for the UI thread to pass results back to the UI
Even though old, got here from Google: consider an IntentService.

Categories

Resources