2011-08-09 10 views
1

J'ai une question. est ce minuteur de code correct?]? ou je peux le faire plus facilementproblème de minuterie Android

package timer2.android; 

import java.util.Timer; 
import java.util.TimerTask; 

import android.app.Activity; 
import android.os.Bundle; 
import android.widget.TextView; 

public class Timer2Activity extends Activity { 

private TextView tv; 
private Timer myTimer; 

/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    tv = (TextView)findViewById(R.id.textView1); 

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

    }, 0, 1000); 
} 

private void TimerMethod() 
{ 

    //This method is called directly by the timer 
    //and runs in the same thread as the timer. 

    //We call the method that will work with the UI 
    //through the runOnUiThread method. 
    this.runOnUiThread(Timer_Tick); 
} 

long mStartTime = System.currentTimeMillis(); 

private Runnable Timer_Tick = new Runnable() { 
    public void run() { 
     final long start = mStartTime; 
     long millis = System.currentTimeMillis() - start; 
     int seconds = (int) (millis/1000); 
     int minutes = (int) (seconds/60); 
     seconds  = seconds % 60; 

     if (seconds < 10) 
     { 
      tv.setText("" + minutes + ":0" + seconds); 
     } 
     else 
     { 
      tv.setText("" + minutes + ":" + seconds);    
     } 

     //a++; 

    //This method runs in the same thread as the UI.    

    //Do something to the UI thread here 

    } 
}; 

}

+0

Ceci est un moyen, et va effectivement faire l'affaire. Bien sûr, il y a beaucoup d'autres façons, mais ils feront tous la même chose. – nhaarman

Répondre

0

ne vois rien de mal ici. Mais vous devez utiliser Handler pour les temporisateurs car il ne crée pas de threads supplémentaires. Voir l'exemple ici: Repeat a task with a time delay?

+0

merci pour votre aide :)) – Peter