Search code examples
javaandroidtimerandroid-handler

Call method when condition is true for certain length of time


I want to create a method whereby if state_i = 1 for time seconds, call method alert_box() , where time is a previously user selected value in seconds.

I'm unsure if I should use a handler.postDelayed or a timer or a while loop to implement this or possibly another method?

The purpose is to show an alert box once a user has their eyes closed for a certain amount of time.

Thank you

eye_tracking method

      private void eye_tracking(Face face) {
            float l = face.getIsLeftEyeOpenProbability();
            float r = face.getIsRightEyeOpenProbability();

            if (l > THRESHOLD || r > THRESHOLD) {
                state_i = 0;
                Log.i(TAG, "onUpdate: Open Eyes Detected");
            } else {
                state_i = 1;
                Log.i(TAG, "onUpdate: Closed Eyes Detected");
             
              //If state_i = 1 for *time* seconds, call method alert_box();

            }

Solution

  • Since eye_tracking() is being called continuously, we can use this to our advantage. We will store the time that the last time the eyes switched state (i.e. was open and now closed). Then in eye_tracking() we will check every time we see a closed eye if the time was elapsed 1000ms in this case, then we can call our function. Whenever the eyes open we will start the cycle again once they are closed.

    Sample Code:

    boolean firstTime = true;
    long lastLowToHighState = 0;
    private void eye_tracking(Face face) {
        float l = face.getIsLeftEyeOpenProbability();
        float r = face.getIsRightEyeOpenProbability();
    
        if (l > THRESHOLD || r > THRESHOLD) {
            state_i = 0;
            firstTime = true;
            Log.i(TAG, "onUpdate: Open Eyes Detected");
        } else {
            if (state_i == 0) {
                lastLowToHighState = SystemClock.elapsedRealtime();
            } else if (firstTime && SystemClock.elapsedRealtime() - lastLowToHighState > 1000) {
                // Used to prevent the function from continously firing
                lastLowToHighState = SystemClock.elapsedRealtime();
                firstTime = false;
                
                // Call Your Method Here
            }
            state_i = 1;
            Log.i(TAG, "onUpdate: Closed Eyes Detected");
        }
    }