ANDROID: Running mutiple async tasks after the first one finishes - android

Basically title. I can run them all in a row or all at once. I need the first one to run to load data for the rest.
Any ideas?

Maybes using handler for the first one so that the code runs on a different thread and trigger the rest when that one completes:
Handler firstTask = new Handler(new Runnable() {
Run() {
//do code
//run rest of tasks
}
}

If you want to make sure that the first AsyncTask has finished and returned the required data before the rest are executed, then override the onPostExecute() method of the first AsyncTask and execute the remaining AsyncTasks inside it.
onPostExecute() is a methode called after the AsyncTask is finished, you can check for the correctness of the received data inside it before executing the other AsyncTasks also inside it.

Your AsyncTasks will be run in the order in which they are submitted and not concurrently, unless you explicitly use the ExecuteOnExecutor method. You can pass data between them accordingly.
Just to be clear, you don't have to do anything at all to make sure that the first task completes before the second (and so on) are run. Each will complete before the next is started, in submission order.

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.

How to do more than one AsyncTask one after another?

Let's say I've two AsyncTask.
AsyncTask_A and AsyncTask_B.
I want to execute AsyncTask_B only when AsyncTask_A is totally finished.
I know one that I could execute AsyncTask_B in AsyncTask_A's postExecute() method.
But.. is there any better way?
In this instance you should create a class that acts a singleton that will handle queuing of these tasks (i.e. a list of AsyncTasks within it) where it tracks if any are running, and if they are, queues them instead. Then within the postExecute() of these tasks, all should callback to the queue object to notify them that they are completed, and then within this callback it should then run the next AsyncTask.
This will allow you to:
Call AsyncTaskA without always having to run AsyncTaskB (removing the hard dependency)
Add more AsyncTasks down the track because the dependency on managing these tasks is on the queue object instead of within the AsyncTasks
Queue<ASyncTask> q;
AsyncTask_A async_a;
AsyncTask_B async_b;
q.add(async_a);
q.add(async_b);
while(!q.empty)
{
AsyncTask task = q.pop();
task.execute();
while(task.isRunning())
{
Thread.sleep(SOME_MILLISECONDS) // You can use wait and notify here.instead of sleep
}
}

android async task usage in depending sequence of tasks

My App contains a function that takes time to load ( parsing files).
THe function is called at multiple user case, i.e. from multiple user triggered condition.
Besides, it is called when onCreate is called.
In simple word, the flow is:
User click/OnCreate trigger
Function to parse file
Post to windows
Other postprocessing
I hope the user can click cancel to stop parsing files.
I tried to use asynctask. I know I can put the function to onPostExecute.
But I assume onPostExecute is just for dismiss progress dialog. Or I have to move a lot of codes ( for different cases) to it. Not a good idea.
I do not suppose user to do anything during parsing files.
So, what is the best way to do so? Despite I know it is not good, I think i have to occupy the UI thread.
In simple word, I want to wait for "parsing files", but i do not want to occupy the UI thread, so user can click cancel.
update:
I tried. however, there is a problem:
I use asynctask. I called:
mTask = new YourAsyncTask().execute();
YourAsyncTask.get(); // this force to wait for YourAsyncTask to return.
DoSomethingBaseOnAsyncTaskResult();
YourAsyncTask.get() hold the UI thread. So, there is not loading dialog, and user cannot click cancel from the dialog. It seems I have to move every line after
mTask = new YourAsyncTask().execute();
to
OnPostExecute()
which i did not prefer to do so because DoSomethingBaseOnAsyncTaskResult() can be very different based on the return result. or else, it becomes do everything in YourAsyncTask()
AsyncTasks should ideally be used for short operations (a few seconds at the most.)
When an asynchronous task is executed, the task goes through 4 steps:
onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time.This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.
onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.
CODING
To start an Async task
mTask = new YourAsyncTask().execute();
and to cancel that task
mTask.cancel(true);
More detail is available here
In order to use the AsyncTask API, one has to follow the steps described below:
Create a class which extends AsyncTask.
Fill in the generic types available as generics in the class for:
the task execution array parameters
progress array parameters
result array parameters
Implement the method doInBackground(Parameters... parameters). This
method must execute the job which is supposed to be quite demanding.
Optionally, one can implement methods for:
cancelling the task - onCancelled(...)
executing tasks before the demanding task - onPreExecute(...)
reporting progress - onProgressUpdate(...)
executing activities after the demanding task is finished
-onPostExecute(...).

Async task gets UI stuck

I have 2 async tasks (which does server requests) running just before i leave my activity.
sometimes the activity which runs this async tasks gets stuck until the async tasks finish, and sometimes the next activity shows and gets stuck until the async tasks finishes.
my question is how do i run this task in a way in which my activity's UI doesn't gets stuck (the UI is not dependable on the responses in the async tasks)
You are probably calling AsyncTask.get() somewhere in your activities code. If you call it before the task has finished executing, it will wait untill it does finish (Thus making your UI get stuck).
Can you try this.
Create a ProgressDialog set it to indeterminate and show it.
Call AsyncTask1 and in its PostExecute call AsyncTask2. Make sure you need to call this onUiThread.
In Postexecute of Asynctask2, dismiss the Progress dialog and start the next Activity.
Make sure you start your next activity on the onPostExecute() of the first Async Task. And if you have an Async task in the new activity ,call it as the last item on your onCreate Method. Following these simple rules should help
Write the code in AsyncTask doInBackground() only and call it. So that you can check whether it is accessing any UI.
eg: TestAsync extends AsyncTask...
TestAsync async = new TestAsync();
async.execute();
Try this.
Normally, AsyncTask should run in separate thread. If you create two instance. and call execute, It should execute independently. But there may be only one thread available, So it should wait(In lower version, pool size is 1.).
#TargetApi(Build.VERSION_CODES.HONEYCOMB) // API 11
void startMyTask(AsyncTask asyncTask) {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
else
asyncTask.execute(params);
}
Other way is, You should run it in normal Thread.
you are must be calling 2 activities at a time in your activity
so either you must use synchronized class or function to call asynk task
or you must use singleton class to call that asynk task so that api is called in synchronized manner
as asynk task uses main ui thread to complete the task so that can be the reason that activity is getting stuck

One difference between handler and AsyncTask in Android

Why can an AsyncTask perform only one job? For example,
task = new SubAsyncTask(...); // assume the parameter is correct.
task.execute(...) //
task.execute(...)// calling once again, it throws exeception.
But a Handler can continously perform more than one task:
hd = new Handler(...); // assume the parameter is correct
hd.sendMessage(...); //
hd.sendMessage(...);// no exeception is thrown.
Is an AasyncTask object for a one-time job only? If I don't want to create multiple object for similar task, should I choose Handler?
Handler and AsyncTasks are way to implement multithreading with UI/Event Thread.
Handler allows to add messages to the thread which creates it and It also enables you to schedule some runnable to execute at some time in future.
Async task enables you to implement MultiThreading without get Hands dirty into threads. Async Task provides some methods which need to be defined to get your code works. in onPreExecute you can define code, which need to be executed before background processing starts. doInBackground have code which needs to be executed in background, in doInBackground we can send results to multiple times to event thread by publishProgress() method, to notify background processing has been completed we can return results simply. onProgressUpdate() method receives progress updates from doInBackground method, which is published via publishProgress method, and this method can use this progress update to update event thread, onPostExecute() method handles results returned by doInBackground method.
So, you dont need to call execute method on AsyncTask multiple TImes, instead you can invoke publishProgress.
Because that is how the class was designed. The idea is: do something with UI (show progress dialog, etc.), do work on background thread and return results, update UI. The Handler is fundamentally different: it lets you post messages, but it does not create a background thread for you. If you don't like how AsyncTask works, build something similar by using threads/executors and handlers.

Categories

Resources