You can use a timer and a handler to achieve it. In the example below, a textual representation is used to display the duration in the format 00min: 00sec. I use this in the background, but you can also use it in action.
public TextView timerTextView; private long startHTime = 0L; private Handler customHandler = new Handler(); long timeInMilliseconds = 0L; long timeSwapBuff = 0L; long updatedTime = 0L; private Runnable updateTimerThread = new Runnable() { public void run() { timeInMilliseconds = SystemClock.uptimeMillis() - startHTime; updatedTime = timeSwapBuff + timeInMilliseconds; int secs = (int) (updatedTime / 1000); int mins = secs / 60; secs = secs % 60; if (timerTextView != null) timerTextView.setText("" + String.format("%02d", mins) + ":" + String.format("%02d", secs)); customHandler.postDelayed(this, 0); } };
Where do you start recording:
...... this.mediaRecorder.start() startHTime = SystemClock.uptimeMillis(); customHandler.postDelayed(updateTimerThread, 0);
Where do you stop recording:
mediaRecorder.stop() timeSwapBuff += timeInMilliseconds; customHandler.removeCallbacks(updateTimerThread);
source share