how to add video timer in android
Categories:
Implementing a Video Timer in Android Applications

Learn how to add a customizable video timer to your Android applications, enabling features like auto-pause, countdowns, and progress tracking for media playback.
Adding a video timer to an Android application can significantly enhance the user experience. Whether you need to display the remaining time, implement an auto-pause feature after a certain duration, or simply show the current playback position, a well-integrated timer is crucial. This article will guide you through the process of implementing a video timer using Android's MediaPlayer
or ExoPlayer
and updating the UI in real-time.
Understanding Video Playback and Timers
Before diving into the implementation, it's important to understand how video playback works in Android and how to synchronize a timer with it. Android provides MediaPlayer
for basic video playback and ExoPlayer
for more advanced, customizable media handling. Both offer methods to get the current position and duration of the media. A timer typically involves periodically querying these values and updating a TextView
or a custom progress bar.
sequenceDiagram participant User participant AndroidApp participant VideoPlayer participant TimerUI User->>AndroidApp: Starts video playback AndroidApp->>VideoPlayer: initialize() & play() loop Timer Update Loop AndroidApp->>VideoPlayer: getCurrentPosition() VideoPlayer-->>AndroidApp: current_ms AndroidApp->>VideoPlayer: getDuration() VideoPlayer-->>AndroidApp: total_ms AndroidApp->>TimerUI: updateDisplay(current_ms, total_ms) TimerUI-->>User: Shows time (e.g., 0:30 / 2:15) AndroidApp->>AndroidApp: Wait for interval (e.g., 1 second) end User->>AndroidApp: Pauses/Stops video AndroidApp->>VideoPlayer: pause()/stop() AndroidApp->>TimerUI: stopUpdates()
Sequence diagram for video timer update process
Implementing a Basic Timer with Handler and Runnable
The most common way to implement a periodic timer in Android is by using a Handler
and a Runnable
. The Runnable
will contain the logic to update the timer UI, and the Handler
will post this Runnable
to be executed repeatedly at a specified interval. This approach ensures UI updates happen on the main thread safely.
import android.os.Handler;
import android.widget.TextView;
import android.media.MediaPlayer;
public class VideoTimer {
private Handler handler = new Handler();
private Runnable runnable;
private MediaPlayer mediaPlayer;
private TextView timerTextView;
public VideoTimer(MediaPlayer player, TextView textView) {
this.mediaPlayer = player;
this.timerTextView = textView;
initRunnable();
}
private void initRunnable() {
runnable = new Runnable() {
@Override
public void run() {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
int currentPosition = mediaPlayer.getCurrentPosition();
int duration = mediaPlayer.getDuration();
timerTextView.setText(formatTime(currentPosition) + " / " + formatTime(duration));
}
handler.postDelayed(this, 1000); // Update every 1 second
}
};
}
public void startTimer() {
handler.post(runnable);
}
public void stopTimer() {
handler.removeCallbacks(runnable);
}
private String formatTime(int milliseconds) {
int seconds = (milliseconds / 1000) % 60;
int minutes = (milliseconds / (1000 * 60)) % 60;
int hours = (milliseconds / (1000 * 60 * 60)) % 24;
if (hours > 0) {
return String.format("%02d:%02d:%02d", hours, minutes, seconds);
} else {
return String.format("%02d:%02d", minutes, seconds);
}
}
}
Java code for a basic video timer using Handler and Runnable.
ExoPlayer
, you can use player.getCurrentPosition()
and player.getDuration()
similarly. ExoPlayer
also offers Player.Listener
callbacks for state changes, which can be useful for starting/stopping the timer.Integrating the Timer into Your Activity/Fragment
Once you have the VideoTimer
class, you need to integrate it into your Activity
or Fragment
where the video playback occurs. This involves initializing the MediaPlayer
or ExoPlayer
, setting up your VideoView
or PlayerView
, and then creating and managing an instance of your VideoTimer
.
<!-- activity_main.xml or fragment_video.xml -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<VideoView
android:id="@+id/video_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true" />
<TextView
android:id="@+id/timer_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_margin="16dp"
android:textColor="#FFFFFF"
android:textSize="18sp"
android:background="#80000000"
android:padding="8dp"
android:text="00:00 / 00:00" />
</RelativeLayout>
Layout XML for VideoView
and TextView
for the timer.
import android.net.Uri;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.VideoView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private VideoView videoView;
private TextView timerTextView;
private VideoTimer videoTimer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
videoView = findViewById(R.id.video_view);
timerTextView = findViewById(R.id.timer_text_view);
// Set up MediaController for basic playback controls
MediaController mediaController = new MediaController(this);
mediaController.setAnchorView(videoView);
videoView.setMediaController(mediaController);
// Set video URI (replace with your video source)
String videoPath = "android.resource://" + getPackageName() + "/" + R.raw.sample_video;
Uri uri = Uri.parse(videoPath);
videoView.setVideoURI(uri);
videoView.setOnPreparedListener(mp -> {
// Initialize and start the timer once the video is prepared
videoTimer = new VideoTimer(mp, timerTextView);
videoTimer.startTimer();
videoView.start(); // Start playback
});
videoView.setOnCompletionListener(mp -> {
// Stop the timer when video completes
if (videoTimer != null) {
videoTimer.stopTimer();
}
timerTextView.setText("00:00 / 00:00"); // Reset timer display
});
}
@Override
protected void onPause() {
super.onPause();
if (videoTimer != null) {
videoTimer.stopTimer(); // Stop timer when activity is paused
}
}
@Override
protected void onResume() {
super.onResume();
if (videoTimer != null && videoView.isPlaying()) {
videoTimer.startTimer(); // Restart timer if video is playing and activity resumes
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (videoTimer != null) {
videoTimer.stopTimer(); // Ensure timer is stopped to prevent memory leaks
}
if (videoView != null) {
videoView.stopPlayback();
}
}
}
Integrating the VideoTimer
into an AppCompatActivity
.
Handler
callbacks (handler.removeCallbacks(runnable)
) in onPause()
or onDestroy()
to prevent memory leaks and unnecessary background processing when your activity is not active.Advanced Timer Features: Auto-Pause and Countdown
Beyond simple progress display, you can extend the timer to implement features like auto-pausing after a set duration or displaying a countdown. This involves adding conditional logic within your Runnable
.
public class VideoTimer {
// ... (previous code)
private long autoPauseDurationMillis = -1; // -1 for no auto-pause
public void setAutoPauseDuration(long durationSeconds) {
this.autoPauseDurationMillis = durationSeconds * 1000;
}
private void initRunnable() {
runnable = new Runnable() {
@Override
public void run() {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
int currentPosition = mediaPlayer.getCurrentPosition();
int duration = mediaPlayer.getDuration();
// Update display for current/total time
timerTextView.setText(formatTime(currentPosition) + " / " + formatTime(duration));
// Implement auto-pause logic
if (autoPauseDurationMillis != -1 && currentPosition >= autoPauseDurationMillis) {
mediaPlayer.pause();
stopTimer(); // Stop timer after pausing
// Optionally, show a message to the user
// Toast.makeText(context, "Video paused after " + formatTime(autoPauseDurationMillis), Toast.LENGTH_SHORT).show();
}
}
handler.postDelayed(this, 1000); // Update every 1 second
}
};
}
// ... (rest of the class)
}
Modifying VideoTimer
to include an auto-pause feature.
1. Set up your layout
Add a VideoView
(or PlayerView
for ExoPlayer) and a TextView
to your activity's or fragment's layout XML.
2. Initialize media player
In your Activity
or Fragment
, initialize MediaPlayer
or ExoPlayer
and set its data source. Wait for the onPreparedListener
callback.
3. Create VideoTimer
instance
Once the media player is prepared, create an instance of your VideoTimer
class, passing the MediaPlayer
object and the TextView
.
4. Start and stop the timer
Call videoTimer.startTimer()
when playback begins (e.g., in onPreparedListener
) and videoTimer.stopTimer()
when playback pauses, stops, completes, or when the activity is paused/destroyed.
5. Handle lifecycle events
Ensure startTimer()
and stopTimer()
are called appropriately within your Activity
or Fragment
lifecycle methods (onResume()
, onPause()
, onDestroy()
) to manage resources and prevent leaks.