Reputation: 4216
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
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
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
Reputation: 7486
You could use a Timer to schedule a TimerTask each second.
beginning time - current time
)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