Reputation: 3
In my app i get weather info from internet in asynctask, but sometimes server is a bit laggy, and i want to make up to 10 requests (if previous was unsuccesful) with 10 second waiting between requests. But when i make my asynctask wait 10 sec.(modeling not responding server), main thread(user interface) freezes until asynctask finishes it's job(make 10 rounds of requests).
here is the code where i make and execute asynctask
WeatherGetter wg = new WeatherGetter();
wg.execute(url);
try {
weather = wg.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
and this is where i make it wait
if (cod != 200) {
synchronized (WeatherGetter.this) {
try {
WeatherGetter.this.wait(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Upvotes: 0
Views: 627
Reputation: 28484
Try this way
do not wait the thread
call same function recursively if code!=200 like this
private void loadWhetherData(final int count) {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
WeatherGetter wg = new WeatherGetter();
wg.execute(url);
try {
weather = wg.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
if (cod != 200 && count<10) {
loadWhetherData(++count);
}
return null;
}
}.execute();
}
Call
This method will calls 10 times until not suceess
loadWhetherData(1);
Upvotes: 2