我在活动中启动了一个AsyncTask ..服务器的任务请求检查用户信息是否经过验证。除非服务器返回user_validated或手动取消,否则此任务将永久运行。
这里是doInBackground()代码:
@Override
protected ApiResult doInBackground(Context... objects) {
AccountState accountState = AccountState.getInstance();
ApiResult result = null;
boolean isEmailValidated = false;
while (!isEmailValidated) {
if (isCancelled()) break;
result = new MyApi().emailValidated(accountState.getAccessToken());
if (result != null) {
MyApi.EmailValidatedResult emailValidatedResult =
MyApi.parseEmailValidatedResult(result.getResponse());
if (emailValidatedResult != null && emailValidatedResult.getValidated()) {
isEmailValidated = true;
} else {
// token is not valid, sleep for RETRY_DELAY and try again
try {
Thread.sleep(RETRY_DELAY);
} catch (InterruptedException e) {
MyLogger.e(e, "Sleep between retry attempts threw InterruptedException!");
}
}
} else {
MyLogger.d("email_validated returned null");
}
}
return result;
}
由于此任务将继续重试,我希望它仅在Activity可见时运行。所以我试图在Activity onPause()时取消任务:
@Override
public void onPause() {
super.onPause();
if (mCurrentTask != null) {
mCurrentTask.cancel(true);
mCurrentTask = null;
}
}
问题是..如果在执行mCurrentTask.cencel(true)
时调用Thread.sleep()
,则会导致InterruptedException
..我不知道是否可以。以及如何在不抛出异常的情况下很好地处理它。