Marl
Marl

Reputation: 1504

Is there a Timer functionality in android? (Not the java.util.Timer)

Is there a timer functionality or timer that is a subclass of View in android that can be use to keep track the playing time of the user?

If I must build one, is it good to build a Thread or Runnable class that have a loop that put itself to sleep for 1000ms (Thread.sleep(1000)) then update itself. e.g.

public class TimerThread extends Runnable{

    private int time;
    boolean run = true;

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

Upvotes: 1

Views: 279

Answers (4)

a.ch.
a.ch.

Reputation: 8390

Just to provide more options, here is another approach: Updating the UI from a Timer

Upvotes: 0

Maurice
Maurice

Reputation: 6433

This might be helpful.

http://developer.android.com/reference/android/widget/Chronometer.html

I think you might need to Google for an example never really used it myself but I've heard of it.

Upvotes: 1

ndgreen
ndgreen

Reputation: 167

Here is some code I use in one of my games. Hope it helps

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

Upvotes: 1

Related Questions