2012-02-21 66 views
1

是否有一個定時器功能或計時器是Android的View的子類,可用於跟蹤用戶的播放時間?在android中是否有Timer功能? (不是java.util.Timer)

如果我必須構建一個,建立一個Thread或Runnable類有一個讓自己睡眠1000ms的線程(Thread.sleep(1000)),然後自行更新是很好的。例如

public class TimerThread extends Runnable{ 

    private int time; 
    boolean run = true; 

    public void run(){ 
     while(run){ 
      //update the View here 
      Thread.sleep(1000); 
      time++; 
     } 
    } 
} 
+0

這是一直在變化和顯示或只是顯示在遊戲結束後? – Maurice 2012-02-21 09:30:37

+0

一直在改變,就像在掃雷遊戲上的定時器 – Marl 2012-02-21 09:35:34

回答

1

下面是我在我的一個遊戲中使用的一些代碼。希望它有幫助

MyCount counter = new MyCount(30000,10); //set to 30 seconds 
counter.start(); 

public class MyCount extends CountDownTimer{ 
    long time=0; 
    public MyCount(long millisInFuture, long countDownInterval) { 
    super(millisInFuture, countDownInterval); 
    } 
    @Override 
    public void onFinish() { 
    clock.setText("You lose!"); //clock is a textfield in the game 
    restart(); //call you own restart method 
    } 
    @Override 
    public void onTick(long millisUntilFinished) { 
    DecimalFormat df=new DecimalFormat("#.##"); //import java.text.DecimalFormat; 
    clock.setText("Left: "+ df.format(millisUntilFinished/1000.0)); 
    time=millisUntilFinished; 
    } 
    public long getTime(){ 
     return time; 
    } 
    }