I am trying to implement exponential backoff for retrying failed http calls by scheduling a thread with handler.postDelayed(...)
every time my request fail. The problem is that I am doing this from an IntentService which dies after scheduling the first thread so the handler is not able to call itself. I am getting the following error:
java.lang.IllegalStateException: Handler (android.os.Handler) {2f31b19b} sending message to a Handler on a dead thread
My class with the IntentService:
@Override
protected void onHandleIntent(Intent intent) {
......
Handler handler = new Handler();
HttpRunnable httpRunnable = new HttpRunnable(info, handler);
handler.postDelayed(httpRunnable, 0);
}
My custom 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;
}
}
}
}
Is there a way to keep my handler alive? What would be the best/cleanest way for scheduling my http retries with an exponential backoff?