How to implement CountDownTimer Class in Xamarin C# Android?

22,449

Why not use System.Timers.Timer for this?

private System.Timers.Timer _timer;
private int _countSeconds;

void Main()
{
    _timer = new System.Timers.Timer();
    //Trigger event every second
    _timer.Interval = 1000;
    _timer.Elapsed += OnTimedEvent;
    //count down 5 seconds
    _countSeconds = 5;

    _timer.Enabled = true;
}

private void OnTimedEvent(object sender, System.Timers.ElapsedEventArgs e)
{
    _countSeconds--;

    //Update visual representation here
    //Remember to do it on UI thread

    if (_countSeconds == 0)
    {
        _timer.Stop();
    }
}

An alternative way would be to start an async Task, which has a simple loop inside and cancel it using a CancellationToken.

private async Task TimerAsync(int interval, CancellationToken token)
{
    while (token.IsCancellationRequested)
    {
        // do your stuff here...

        await Task.Delay(interval, token);
    }
}

Then start it with

var cts = new CancellationTokenSource();
cts.CancelAfter(5000); // 5 seconds

TimerAsync(1000, cts.Token);

Just remember to catch the TaskCancelledException.

Share:
22,449
D micro
Author by

D micro

Updated on December 14, 2020

Comments

  • D micro
    D micro over 3 years

    I am new to Xamarin.Android framework. I am working on count down timer but unable to implement like the java CountDownTimer class. Could anybody please help me out to convert following java code to C# Xamarin android code.

        bar = (ProgressBar) findViewById(R.id.progress);
        bar.setProgress(total);
        int twoMin = 2 * 60 * 1000; // 2 minutes in milli seconds
    
        /** CountDownTimer starts with 2 minutes and every onTick is 1 second */
        cdt = new CountDownTimer(twoMin, 1000) { 
    
            public void onTick(long millisUntilFinished) {
    
                total = (int) ((dTotal / 120) * 100);
                bar.setProgress(total);
            }
    
            public void onFinish() {
                 // DO something when 2 minutes is up
            }
        }.start();