【发布时间】:2015-06-04 17:09:44
【问题描述】:
我正在尝试通过在每次我的请求失败时使用handler.postDelayed(...) 调度一个线程来实现指数退避,以重试失败的 http 调用。问题是我从 IntentService 执行此操作,该 IntentService 在调度第一个线程后死亡,因此处理程序无法调用自身。我收到以下错误:
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 重试的最佳/最干净的方法是什么?
【问题讨论】:
标签: java android multithreading android-handler android-intentservice