我試圖通過每次請求失敗時調度線程handler.postDelayed(...)
來重試失敗的http調用來實現指數退避。問題在於,我正在調度第一個線程之後死亡的IntentService,因此處理程序無法自行調用。我收到以下錯誤:從IntentService調度遞歸處理程序以重試http調用
java.lang.IllegalStateException: Handler (android.os.Handler) {2f31b19b} sending message to a Handler on a dead thread
我班與IntentService:
@Override
protected void onHandleIntent(Intent intent) {
......
Handler handler = new Handler();
HttpRunnable httpRunnable = new HttpRunnable(info, handler);
handler.postDelayed(httpRunnable, 0);
}
我定製的Runnable:
public class HttpRunnable implements Runnable {
private String info;
private static final String TAG = "HttpRunnable";
Handler handler = null;
int maxTries = 10;
int retryCount = 0;
int retryDelay = 1000; // Set the first delay here which will increase exponentially with each retry
public HttpRunnable(String info, Handler handler) {
this.info = info;
this.handler = handler;
}
@Override
public void run() {
try {
// Call my class which takes care of the http call
ApiBridge.getInstance().makeHttpCall(info);
} catch (Exception e) {
Log.d(TAG, e.toString());
if (maxTries > retryCount) {
Log.d(TAG,"%nRetrying in " + retryDelay/1000 + " seconds");
retryCount++;
handler.postDelayed(this, retryDelay);
retryDelay = retryDelay * 2;
}
}
}
}
有沒有辦法讓我的處理程序還活着嗎?用指數回退安排我的http重試最好/最乾淨的方式是什麼?
非常好,合乎邏輯,謝謝!我不得不通過將getService的最後一個參數更改爲'PendingIntent.FLAG_UPDATE_CURRENT' – Crocodile