2013-06-25 8 views
7

Sono nuovo di Xamarin.Android framework. Sto lavorando al conto alla rovescia ma non riesco ad implementare come il java CountDownTimer class. Qualcuno potrebbe per favore aiutarmi a convertire il seguente java code in codice X Xamarin per Android.Come implementare la classe CountDownTimer in 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

Dov'è il codice? –

+0

ho aggiunto il link..grazie per la risposta –

+0

puoi dirmi come eseguire questo codice su thread xamarin android –

risposta

22

Perché non utilizzare System.Timers.Timer per questo?

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(); 
    } 
} 

Un modo alternativo sarebbe quello di avviare un asincrona Task, che ha un semplice ciclo interno e annullarlo utilizzando un CancellationToken.

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

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

Poi iniziare con

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

TimerAsync(1000, cts.Token); 

Basta ricordarsi di prendere il TaskCancelledException.

+2

grazie per la risposta, puoi dirmi come eseguire questo codice su ui thread xamarin android? –

+7

'RunOnUiThread (() => {/ * UI aggiornamento qui * /});' – Cheesebaron

Problemi correlati