clayton33
clayton33

Reputation: 4216

create a simple digital timer in android

I'm basically looking to just keep track of seconds and minutes starting at 0:00 from when the app starts, and display it in a TextView what would be the best method of doing this?

Upvotes: 1

Views: 15982

Answers (3)

jimmy cool
jimmy cool

Reputation: 147

    Runnable run = new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            long millis = System.currentTimeMillis() - starttime;
               int seconds = (int) (millis / 1000);
               int minutes = (seconds%3600)/60;
               int hours = seconds / 3600;
               seconds     = seconds % 60;

               et1.setText(String.format("%02d:%02d:%02d",hours, minutes, seconds));
     //          et2.setText(String.format("%02d:%02d:%02d",hours, minutes, seconds));
      //         et3.setText(String.format("%02d:%02d:%02d",hours, minutes, seconds));

               h2.postDelayed(this, 500);
        }
    };

    class firstTask extends TimerTask {

        public void run() {
            handler.sendEmptyMessage(0);
        }
};  

try it in ur program...!

Upvotes: 2

Khawar
Khawar

Reputation: 5227

As timer starts a non-UI Thread, i'll prefer not to use it for updating TextView. In your case Timer can be replaced by the Handler class. And you can also avoid the overhead of this new non-UI thread. Here is an example:

private Handler mHandler = new Handler();

OnClickListener mStartListener = new OnClickListener() 
{
   public void onClick(View v)
   {
      if (mStartTime == 0L) 
      {
        mStartTime = System.currentTimeMillis();
        mHandler.removeCallbacks(mUpdateTimeTask);
        mHandler.postDelayed(mUpdateTimeTask, 100);
      }
   }
};

.........

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

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

     mHandler.postAtTime(this,start + (((minutes * 60) + seconds + 1) * 1000));
   }
}; 

Upvotes: 5

maid450
maid450

Reputation: 7486

You could use a Timer to schedule a TimerTask each second.

  • first you take the beginning time
  • then in the TimerTask job you get the time spent (beginning time - current time)
  • you format this difference as a String of the form xx:xx with DateFormat
  • you update the TextView with this String

I'm not sure if you could have problems when updating the TextView from the TimerTask job as it doesn't run in UI thread, in that case you can use Activity.runOnUiThread to do this

Upvotes: 3

Related Questions