I have an existing code which has an Async Task used for some request-response. In the post execute method it sets the parsed data into some db.
Now I need to modify this code in such a way that at app launch, the data gets downloaded one by one. i.e. I need to execute task A, then on its full completion (even the data is set) I need to start task B and so on for around 12 tasks.
Note: I need to finish the "post execute" as well before starting the next task.
I am not sure how to do this. Please suggest.
You can do it with myAsyncTask.executeOnExecutor (SERIAL_EXECUTOR)
AsyncTask a = new AsyncTask();
AsyncTask b = new AsyncTask();
AsyncTask c = new AsyncTask();
a.executeOnExecutor (SERIAL_EXECUTOR);
b.executeOnExecutor (SERIAL_EXECUTOR);
c.executeOnExecutor (SERIAL_EXECUTOR);
Now the exection order will be a -> b -> c;
This one gets a bit messy..
Configuring a AsyncTask with SERIAL_EXECUTOR will indeed force serial execution of background logic,
that is, the logic contained within the doInBackground() calls.
SERIAL_EXECUTOR makes no guarantees as to when the onPostExecute() will be invoked.
Executing a set of AsyncTask in SERIAL_EXECUTOR mode may result in onPostExecute() of task A being executed after the doInBackground() of task B.
If the latter demand is not crucial to your system, just use SERIAL_EXECUTOR and be happy.
But, if it is, you will need to change your architecture in a way that will force such demand.
one way of doing so will be as follows:
class MyAsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
// do background work
return null;
}
@Override
protected void onPostExecute(Void args) {
// update UI here
new MyNextAsyncTask.execute(..); // <---------- start next task only after UI update has completed
}
}
That is: you will wait for the UI update of one operation to complete before starting the next one.
Another way, which I would probably prefer, would be to manage th entire task flow within a single thread that internally perform att background tasks A -> B -> C .... and, in between, issues UI update commands and waits on a ConditionVariable for these tasks to complete
new Thread() {
ConditionVariable mCondition = new ConditionVariable(false);
void run() {
do_A();
runonUIThread(updateAfter_A_Runnable);
mPreviewDone.block(); // will be release after updateAfterA_Runnable completes!
do_B();
runonUIThread(updateAfter_B_Runnable);
mPreviewDone.block(); // will be release after updateAfter_B_Runnable completes!
etc..
}
}
Hope it helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With