SystemClock.elapsedRealtimeからstartTimeを引いた時間を表示しています。
参考:https://developer.android.com/reference/android/os/SystemClock.html
リフェレンス
handler:A Handler allows you to send and process Message and Runnable objects associated with a thread’s MessageQueue. Each Handler instance is associated with a single thread and that thread’s message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it — from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.
SimpleDateFormat:is a concrete class for formatting and parsing dates in a locale-sensitive manner. It allows for formatting (date -> text), parsing (text -> date), and normalization.
package self.stopwatchapp; import android.icu.text.SimpleDateFormat; import android.os.Handler; import android.os.SystemClock; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import java.util.Locale; public class MainActivity extends AppCompatActivity { private long startTime; private long elapsedTime = 0l; private Handler handler = new Handler(); private Runnable updateTimer; private Button startButton; private Button stopButton; private Button resetButton; private TextView timerLabel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); startButton = (Button) findViewById(R.id.startButton); stopButton = (Button) findViewById(R.id.stopButton); resetButton = (Button) findViewById(R.id.resetButton); timerLabel = (TextView) findViewById(R.id.timerLabel); setButtonState(true, false, false); } public void setButtonState(boolean start, boolean stop, boolean reset){ startButton.setEnabled(start); stopButton.setEnabled(stop); resetButton.setEnabled(reset); } public void startTimer(View view){ // starttime startTime = SystemClock.elapsedRealtime(); //起動からの経過時間 // 現在の経過時間 // Handler -> Runnable -> UI updateTimer = new Runnable(){ @Override public void run() { long t = SystemClock.elapsedRealtime() - startTime + elapsedTime; SimpleDateFormat sdf = new SimpleDateFormat("mm:ss.SSS", Locale.US); timerLabel.setText(sdf.format(t)); handler.removeCallbacks(updateTimer); handler.postDelayed(updateTimer, 10); } }; handler.postDelayed(updateTimer, 10); // button setButtonState(false, true, false); } public void stopTimer(View view){ elapsedTime += SystemClock.elapsedRealtime() - startTime; handler.removeCallbacks(updateTimer); setButtonState(true, false, true); } public void resetTimer(View view) { elapsedTime = 0l; timerLabel.setText("00:00:000"); setButtonState(true, false, false); } }