1

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 start() method.

//...

/**
 * 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--;
            }
        }
    }
};

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 repeatCounter, for example, 2 times or 3 times. However, when the second sendRequest() is called in onWrite(), threadid=1: stack overflow on call is thrown. I guess it is a recursive problem.

mWrite is a callback to mAccessor.Write();

How can I solve this?

1 Answer 1

0

I've spotted 2 possible issues:

  1. decrement repeatCounter before calling sendRequest again.

  2. the stop case should be - "if (repeatCounter <= 0)" not "==" to avoid possible issues where you decrement twice before getting to the point of checking the value at repeatCounter

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.