Handler PostDelayed method runs faster than 1 second when given a delay of 1 second

Viewed 56

I have a Handler postDelayed method, i have passed 1 second of delay and calling it again and again. I am also printing the seconds passed every second, but what i am observing is that it prints faster than 1 second. So in a second, its printing 2-3 seconds.

This is the code:

runOnUiThread(new Runnable() {
  @Override
  public void run() {
    Handler h = new Handler();
    h.postDelayed(new Runnable() {
      @Override
      public void run() {
        Log.d(TAG, "Timer running...");
        if (startCounter) {
          timeCheck -= 1000;
          //check if device is connected every second
          //if it is connected then reset timer
          Log.d(TAG, "Time: " + timeCheck / 1000 + " sec");
          if (Constants.IS_CONNECTED) {
            timeCheck = 180000;
            updateFlutter(1);
            Log.d(TAG, "Device is connected");
          } else {
            Log.d(TAG, "Disconnected but might be in sleep mode");
            if (timeCheck <= 0) {
              //                            not connecting
              //                            device has been disconnected
              Log.d(TAG, "Fully Disconnected");
              updateFlutter(0);
              startCounter = false;
              mHandler.post(new Runnable() {
                @Override
                public void run() {
                  Toast.makeText(getApplicationContext(), "Device DISCONNECTED", Toast.LENGTH_SHORT).show();
                }
              });
            }
          }
        }
        h.postDelayed(this, 1000);
      }
    }, 0);
  }
});

1 Answers

I understood the problem, so basically what was happening is that a new thread was being called everytime the startTimer method was being called. Now multiple threads were trying to decrease the value of timeCheck, and hence time was passing way fast than it should have. For this to resolve, i changed the global variable to local variable and it solved the problem for me.

Related