的解決方案是從調用的AsyncTask一個TimerTask
protected class MyTimerTask extends TimerTask {
@Override
public void run() {
(new AsyncTask<Void, Void, String>() {
@Override
protected void onPreExecute() {
super.onPreExecute();
...
}
@Override
protected String doInBackground(Void... params) {
//invoke REST service
....
return "";
}
@Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
//post execute operations
...
}
}).execute();
}
}
,如果你害怕調用服務器的時間太長,然後要求他們重疊,可以輸入一個的AtomicBoolean信號量(同步)以下列方式:
旗語聲明
private final AtomicBoolean isRunning = new AtomicBoolean(false);
的TimerTask用旗語
protected class MyTimerTask extends TimerTask {
@Override
public void run() {
//if isRunning is true does not execute the task
if (isRunning.get()) return;
(new AsyncTask<Void, Void, String>() {
@Override
protected void onPreExecute() {
super.onPreExecute();
//active flag isRunning
isRunning.set(true);
...
}
@Override
protected String doInBackground(Void... params) {
....
//invoke REST service
....
return "";
}
@Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
//post execute operations
...
//deactive flag isRunning
isRunning.set(false);
}
}).execute();
}
}
注:小心,當你發現一個錯誤,因爲如果由於某種原因仍處於活動狀態將不再運行的AsyncTask