问题
Does anyone know how to easily arrange multiple calls to an AsyncTask execution in a queue or something and then execute them in a serial fashion?
I want the called async task to wait while the one before it is finished, but is seems I can't accomplish this, even if I test the status of the one currently being executed.
Any ideas how to solve this? I've seen that in the honeycomb API there is a method executeOnExecutor()
with a SERIAL_EXECUTOR
, I guess it implements what I've described. However, I'm not developing for honeycomb.
Thanks!
回答1:
You might try IntentService. From the reference:
IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.
I ran the service from a broadcast receiver as follows:
// Now let the service module do the rest
Intent serviceIntent = new Intent(context, Service.class);
serviceIntent.putExtra(GC.EXTRA_SERVICE_DATA, serviceData);
ComponentName compName = context.startService(serviceIntent)
It worked as advertised. The requests are serialized fine. The service started when a request was received. The service stopped after the last request processed. The requests were processed FIFO.
I created the intentservice using right click on the source package name and selecting New/Class. I used intentservice as the superclass. The constructor has an arguement of 'name'. I changed it to:
public XxxService() {super("XxxService");}
All of the code for the service went into the onHandleIntent function. I didn't have to use any other @Override functions.
Hope this is what you wanted...
Notes: The variable 'context' is a passed parameter in onReceive. I changed the names in the code from XxxxService to 'Service' or 'service'. Finally, I create a class in all my projects called GC. It is a container class for global constants. GC.EXTRA_SERVICE_DATA is a global String defining the extra key.
回答2:
Android versions greater than Honeycomb have made the default executor of Asynctask as serial executor. So if your min. SDK version and the target SDK version are more than 12, Asynctasks will execute in accordance to the calling of their execute function. See my discussion on Asynctask at
https://docs.google.com/document/d/1_zihWXAwgTAdJc013-bOLUHPMrjeUBZnDuPkzMxEEj0/edit?usp=sharing
Hope this helps you...
回答3:
I would do it this way, Have an array or a queue or counter of number of times you want to execute AsyncTAsk(same class of AsyncTask or different class) in an activity, In AsyncTask, onPostExecute(), decrement the counter(or similar data structure) and call the AsyncTask again.
来源:https://stackoverflow.com/questions/6890704/serial-execution-of-multiple-asynctasks