2013-06-25 10 views
7

Jestem nowy w ramach Xamarin.Android. Pracuję nad odliczaniem czasu, ale nie mogę go wdrożyć tak, jak java CountDownTimer class. Czy ktokolwiek może mi pomóc konwertować następujące java code na kod Androida C# Xamarin.Jak zaimplementować klasę CountDownTimer w Xamarin C# 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(); 
+0

Gdzie jest kod? –

+0

Dodałem link .. podziękowania za odpowiedź –

+0

możesz mi powiedzieć, jak uruchomić ten kod na temat XiMin android android –

Odpowiedz

22

Dlaczego nie użyć do tego celu 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(); 
    } 
} 

Alternatywnym rozwiązaniem byłoby, aby rozpocząć asynchronicznie Task, który ma prostą wewnątrz pętli oraz anulować stosując CancellationToken.

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

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

Następnie uruchom go z

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

TimerAsync(1000, cts.Token); 

Wystarczy pamiętać, aby złapać TaskCancelledException.

+2

dzięki za odpowiedź możesz mi powiedzieć, jak uruchomić ten kod na Android XIARIN wątku? –

+7

'RunOnUiThread (() => {/ * aktualizuj interfejs tutaj * /});' – Cheesebaron

Powiązane problemy