What is the sequence of runs for AsyncTask?

2

I need to synchronize data between the server and the client application on Android and for this I created several ASyncTask classes, one synchronizes the Third parties, the other the Financial, Accounts Receivable and Accounts Payable, for example.

I did this to reuse code, which will be used in other services and activities. However, the moment the user synchronizes the first time, in Activity the ASyncTask are executed one below the other, without checking if the top one has finished the business rule.

My question is the following, when a ASyncTask is finished, the bottom one is executed or does it start even before the ASyncTask superiors end the execution?

The problem with this is inconsistency in the Android database, such as the foreign keys, for example when saving the records in SQLite.

    
asked by anonymous 02.09.2015 / 04:12

2 answers

7

You can ensure that AsyncTask's runs in sequence using the executeOnExecutor () to execute each of them.

This method takes as a parameter the Executor that will execute the Task's if it passes the value AsyncTask.SERIAL_EXECUTOR will run sequentially.

ex:

asyncTask1.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);

// asyncTask2 só será executado após asyncTask1 ter terminado.
asyncTask2.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);

Edit:

All that has been said before is true but this is, from the HONEYCOMB version, the way the execute () executes tasks . That is, there is no need to use the executeOnExecutor() method if you want tasks to run in series.

Initially, when they were introduced, AsyncTasks ran in series, in a single thread . From the DONUT version this was changed to a thread pool , allowing you to perform multiple tasks in parallel. The emergence of several compatibility issues, in which old codes stopped working properly, led to the

02.09.2015 / 11:44
3

If you schedule a number of AsyncTask's, there is no guarantee of order of execution. To ensure this order you would have to schedule only the AsyncTask that you want to see executed first, and onPadExecute () you schedule the second task, and so on.

    
02.09.2015 / 04:24