title: How to solve recursive call that causes stack overflow error in Android?
body: <p>I have a scheduled interval task in my Android application. Assume that it is a task of health check to a USB-connected device and it is running every 10 minutes. According to the class code below, the task is started by calling <code>start()</code> method.</p>
  
  <pre><code>//...
  
  /**
   * Handler callback
   */
  private Runnable handlerCallback = new Runnable() {
      @Override
      public void run() {
          sendRequest();
          handler.postDelayed(handlerCallback, interval);
      }
  };
  
  /**
   * Start the repeated task
   */
  public void start() {
      handlerCallback.run();
  }
  
  /**
   * Stop the task
   */
  public void stop() {
      handler.removeCallbacks(handlerCallback);
  }
  
  /**
   * Send request
   */
  public void sendRequest() {
      CmdRequestHealthCheck cmd = new CmdRequestHealthCheck();
      mAccessor.Write(cmd.get(), mWrite);
  }
  
  /**
   * Request Health Check
   */
  protected final WriteCallback mWrite = new WriteCallback() {
      @Override
      public void onWrite(boolean bStatus, Exception oError) {
          if (bStatus) {
              // Success
              repeatCounter = Globals.HEALTH_CHECK_REPEAT;
              Toast.makeText(context, "Success", Toast.LENGTH_LONG).show();
          } else {
              // Fail
              if (repeatCounter == 0) {
                  // finally show error
                  Toast.makeText(context, "Failed", Toast.LENGTH_LONG).show();
                  // if there is error message returned
                  if (oError != null) {
                      Toast.makeText(context, oError.toString(), Toast.LENGTH_LONG).show();
                  }
              } else {
                  // Immediate Retry for xx times
                  sendRequest();
                  repeatCounter--;
              }
          }
      }
  };
  </code></pre>
  
  <p>When a first request failed, the immediate second request will be sent without waiting for the next interval 10 minutes. The immediate next checks will be sent according to <code>repeatCounter</code>, for example, 2 times or 3 times. However, when the second <code>sendRequest()</code> is called in <code>onWrite()</code>, <code>threadid=1: stack overflow on call</code> is thrown. I guess it is a recursive problem. </p>
  
  <p><code>mWrite</code> is a callback to <code>mAccessor.Write()</code>;</p>
  
  <p>How can I solve this?</p>