Android Async Task One After Another
Solution 1:
You can do it with myAsyncTask.executeOnExecutor (SERIAL_EXECUTOR)
AsyncTaska=newAsyncTask();
AsyncTaskb=newAsyncTask();
AsyncTaskc=newAsyncTask();
a.executeOnExecutor (SERIAL_EXECUTOR);
b.executeOnExecutor (SERIAL_EXECUTOR);
c.executeOnExecutor (SERIAL_EXECUTOR);
Now the exection order will be a -> b -> c;
Solution 2:
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:
classMyAsyncTask<Void, Void, Void> {
@OverrideprotectedVoiddoInBackground(Void... params) {
// do background workreturnnull;
}
@OverrideprotectedvoidonPostExecute(Void args) {
// update UI herenewMyNextAsyncTask.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);
voidrun() {
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.
Solution 3:
The implementation depends on your requirement.
If after every call you need to update your UI you can download and save data in
doInBackground()
and the update inonPostExecute()
.If you wanna update your UI just once then download all the data inside a loop inside your
doInBackground()
and also save your data in db there only and finally call youronPostExecute()
just once.If it has nothing to do with updating the UI then you can simply use
Thread
.
NOTE :AsyncTask
order of execution will be serial only aboveHoneyComb
below that it would be parallel.
Post a Comment for "Android Async Task One After Another"