Reputation: 663
I know that Similar questions have been asked before but the solution to those questions will not work for me. The situation is that I have an Array of objects that are each getting sent to uploaded to the server via an asynctask. I need to send each one separately but each object in the list uses the same asynctask so calling task.execute in the onPostExecute() is not an option since that would cause it to infinitely call itself. I have tried something like so
for(each item in list){
task.execute();
while(task.getStatus() != android.os.AsyncTask.Status.FINISHED){
//spin here and wait
}
}
But when doing this it just spins for ever and never leaves the while loop. Any suggestions are greatly appreciated
Upvotes: 2
Views: 5170
Reputation: 3447
Why don't you change your architecture: Make the uploading async task take an array of files to upload and just loop through them?
If you really want to stay this way, just use a lock
object.
Something like:
class MyAsyncClass extends AsyncTask{
static Object lock = new Object();
.......
void doWork(){
synchronized(lock) {
//do stuff
}
}
}
EDIT: I should point out that this does not ensure you, that the doWork()
methods are executed in the order, they were called.
Upvotes: 3
Reputation: 14520
I suggest you should switch to Thread and Executor service to do this. This will give you greater grip on switching between sequential and parallel execution of tasks.
With the help of ExecutorService(Actually a Threadpool manager).
Example :
ExecutorService service = Executors.newFixedThreadPool(1);
service.submit(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
}
});
You can submit as many runnables to this and since the thread count is 1, it will get executed sequentially.
For communicating with UI, you can user Handler.
Upvotes: 1
Reputation: 8870
You could look into using an IntentService, instead of an AsyncTask
-- since launching multiple intents to the same IntentService
will queue up the operations, so the Intent launched before will have to complete before the second onHandleIntent(Intent)
will run.
Upvotes: 0
Reputation: 385
public void onPostExecute(){if(blahblah){
task.execute();
}
}
AKA put an if statement on task.execute so you have control..
Upvotes: 0
Reputation: 49986
From AsyncTask docs:
Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution.
so if you are not >= HONEYCOMB, then maybe switch to use ExecutorService:
ExecutorService executor = Executors.newSingleThreadExecutor();
Upvotes: 6