I have two AsyncTasks. Each one of this has a method to get information from a Backend services, populate a local SQLite table and then call a third AsyncTasks.
The first AsyncTasks it have to be called every 2 hours The second AsyncTasks it have to be called every 8 hours
To do that I use TimerTask like this:
final Handler handlerBS = new Handler();
Timer timerBS = new Timer();
TimerTask taskBS = new TimerTask() {
@Override
public void run() {
handlerBS.post(new Runnable() {
public void run() {
new FetchBackendData1Task().execute();
}
});
}
};
timerBS.schedule(taskBS, 0, 1000 * 60 * 60 * 8);
final Handler handlerBS2 = new Handler();
Timer timerBS2 = new Timer();
TimerTask taskBS2 = new TimerTask() {
@Override
public void run() {
handlerBS2.post(new Runnable() {
public void run() {
new FetchBackendData2Task().execute();
}
});
}
};
timerBS2.schedule(taskBS2, 0, 1000 * 60 * 60 * 8);
The main idea is:
AsyncTasks 1: 1) Start 2) Call backend 3) Return from backend 4) Populate the table 5) Check if AsyncTasks 2 has finish. 5-1) If it is finished, call AsyncTasks 3. 5-2) If it not, don't do anything
AsyncTasks 2: 1) Start 2) Call backend 3) Return from backend 4) Populate the table 5) Check if AsyncTasks 1 has finish. 5-1) If it is finished, call AsyncTasks 3. 5-2) If it not, don't do anything
AsyncTasks 3: 1) Get data from the table filled with AsyncTasks 1 2) Get data from the table filled with AsyncTasks 2 3) Merge the data 4) Use the data.
I tried two ideas
Option 1) Put a Boolean Flag in the Application for each AsyncTasks. When each AsyncTasks start, set the flag in True. When one of the AsyncTasks finish, I check the flag of the other. If it is on false call the AsyncTasks 3, if not, don't do anything
Option 2) set the main method of the AsyncTasks 3 with synchronized flag
If I run the application on debug mode, it works ok.
But if I run the application in normal mode, the first time (when both AsyncTasks start at the same time) something happens and the third AsyncTasks it is not called.
If I check the Tables, both are filled, so I think that there is a problem with the synchronization
I tried putting an small delay on the second AsyncTask. And it works (but I can't use this approach).
Based on those tests, I think that there is some problem with the Synchro or something like that
My questions are: 1) Are one of those approaches right? 2) There is another better way to do that? 3) Can somebody have an idea of why on the first execution it is not working?
Thanks for your time and sorry if my english it is not the best
Aucun commentaire:
Enregistrer un commentaire