title: Cancel AsyncTask when Activity onPause()
body: <p>I start an AsyncTask inside the activity.. The task request from server check if user info is validated. This task will run forever unless server returns user_validated or it's manually cancelled.</p>
  
  <p>Here's the doInBackground() code:</p>
  
  <pre><code>    @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 &amp;&amp; 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;
      }
  </code></pre>
  
  <p>Since this task will keep retry, I want it to run only when Activity is visible. So I tried to cancel the task when Activity onPause():</p>
  
  <pre><code>@Override
  public void onPause() {
      super.onPause();
      if (mCurrentTask != null) {
          mCurrentTask.cancel(true);
          mCurrentTask = null;
      }
  }
  </code></pre>
  
  <p>The problem is.. if <code>mCurrentTask.cencel(true)</code> is called while <code>Thread.sleep()</code> is being executed.. it will cause <code>InterruptedException</code>.. I don't know if that is ok. and how to handle it nicely without throwing exception.</p>