如何在Xamarin C#Android中实现CountDownTimer类?

D m*_*cro 9 c# android xamarin.android xamarin

我是Xamarin.Android框架的新手.我正在计算倒计时器但无法实现像java CountDownTimer.任何人都可以帮我把以下java 代码转换为C#Xamarin android代码.

    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();
Run Code Online (Sandbox Code Playgroud)

Che*_*ron 23

为什么不用System.Timers.Timer这个呢?

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

另一种方法是启动一个异步Task,它内部有一个简单的循环,并使用a取消它CancellationToken.

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

        await Task.Delay(interval, token);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后开始吧

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

TimerAsync(1000, cts.Token);
Run Code Online (Sandbox Code Playgroud)

只记得赶上TaskCancelledException.

  • `RunOnUiThread(()=> {/*在这里更新UI*/});` (7认同)
  • 谢谢你的回复你可以告诉我如何在ui线程xamarin android上运行此代码? (2认同)