Here I have a Timer class to display a timer
public class FourthActivity extends AppCompatActivity { Button startButton, pauseButton; TextView timerValue; Timer timer; int seconds = 0, minutes = 0, hour = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_fourth); bindView(); timer = new Timer(); startButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { if (seconds == 60) { timerValue.setText(String.format("%02d", hour) + ":" + String.format("%02d", minutes) + ":" + String.format("%02d", seconds)); minutes = seconds / 60; seconds = seconds % 60; hour = minutes / 60; } seconds += 1; timerValue.setText(String.format("%02d", hour) + ":" + String.format("%02d", minutes) + ":" + String.format("%02d", seconds)); } }); } }, 0, 1000); } }); } private void bindView() { timerValue = (TextView) findViewById(R.id.timerValue); startButton = (Button) findViewById(R.id.startButton); } }
The layout has one TextView and one button to start the timer. I have a class method Timer scheduleAtFixedRate . The time will be displayed in the form hh: mm: ss.
source share