Android timer is not accurate

So I'm a real newbie with java and android programming. I am trying to make a basketball app for friendly games. Right now I'm doing a dropcol that counts from 24 to 0, plays a sound, and is reset with a button.

public class MainActivity extends Activity {
    private ShotClock shotClock;
    private TextView shotClockTimer;
    private Timer timer = new Timer();
    private Button shotClockReset;
    private final static int interval = 100;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        shotClockTimer = (TextView) findViewById(R.id.shotClock);
        shotClockReset = (Button)findViewById(R.id.shotClockReset);
        shotClock = new ShotClock();
        shotClockReset.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {
                shotClock.shotClockReset();
            }

        });
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                TimerMethod();
            }

        }, 0, interval);

    }

    private void TimerMethod() {
        this.runOnUiThread(Timer_Tick);
    }

    private Runnable Timer_Tick = new Runnable() {
        public void run() {
            shotClock.advanceClock();
            shotClockTimer.setText(String.format("%.1f",shotClock.getSeconds()));

        }
    };
}

      

The idea is that I have a timer that runs every 0.1 seconds and updates the clock accordingly. This works great, the hours are counted from 24 to 0 and reset as expected. My problem is that it doesn't - I tested it with 3 other timers and it is always a little slower: by the time the other timers reach 0, this one is only ~ 1-1.5 seconds long. What can I do to make it more accurate besides changing the spacing in a primitive way? Please be friendly as I am new :) Thanks for the help!

+3


source to share


1 answer


This is due to internal scheduling, the scheduler calls this method approximately every 0.1 seconds. However, the system itself is accurate. Use System.currentTimeMillis () to fix this error.

Android itself is not a real-time application, but the system is the most accurate source you can get.

So programming accurate stopwatches for sports neighbors, for example, is not mandatory for android;)



Just loop and calculate the offset of the milliseconds, if the offset is reached, call the method.

But think about imprecision too. Calculate the offset always from the start (1 * 0.1 seconds, 2 * 0.1 seconds ...), not the last value, so minimize the inaccuracy here.

+5


source







All Articles