This post was last Updated on June 8, 2023 by Himanshu Tyagi to reflect the accuracy and up-to-date information on the page.
Do you want to work with Videos in your Android application? If yes, you will have to work on the Android VideoView element. With the help of VideView, you can load videos and choose to play them based on the user’s interaction.
In this tutorial, you will learn how to create a simple Android VideoView application using Android Studio. You will understand how to use this element to work with video files in your Android application.
You can also download the sample VideoView application code from our GitHub repository if you don’t want to code while following the tutorial and quickly want to see your Android VideoView application in action.
If you have any queries, you can contact us at [email protected] or leave your questions in the comments section, and we will do our best to assist you.
Also Read: Android WebView Tutorial With An Example Project + Download Code.
Creating a simple VideoView Android application
Using Android VideView, you can either play videos from various resources. VideoView can easily handle multiple format video files from local resources or the Internet.
However, when users switch between the apps, VideoView doesn’t retain its state. For example, you might have noticed that if you close Netflix and open it again after some time, it plays the video right from your left position.
Well, this isn’t the case with VideoView. To retain states, you must explicitly use onSaveInstanceState(Bundle) and onRestoreInstanceState(Bundle).
So let’s get started.
Also Read: Android ListView Tutorial With Example Project.
Step 1: Creating a new Android Studio project
Fire up your Android Studio Application and click on Start a new Android Studio project.
You will now see the Android Studio screen, where you must select your project template.
To keep things simple, select an Empty Activity and click the Next button, as shown in the screenshot below.
Also Read: 15 Best Websites to Learn Android App Development
Next, you will have to configure the project settings of your VideoView application. Enter your Application Name and Package Name, and click Finish.
Note: Package Name is a unique identifier for every Android application.
Another critical thing to note is that you can change the Minimum SDK required for your application to run. Therefore, select one that is compatible with most available Android devices.
Once you click the Finish button, your empty activity of the VideoView application will load. Wait a few minutes for the Gradle project to build, and once it is done, you can move to the next step.
Also Read: Android app to execute code in 23+ programming languages.
Step 2: Adding VideoView to Activity XML
There are two ways of doing this: add VideoView by just drag-and-drop or follow the code method.
A. Drag and Drop
Search VideoView in the search box. Then drag the widget onto the activity screen. And you are done.
Also Read: Android App Architecture: How to Do It Right?
B. Code
Open activity_main.xml and add this code.
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <VideoView android:id="@+id/mVideoView" android:layout_width="fill_parent" android:layout_height="200dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.55" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
Step 3: Loading a video in the VideoView application
Open MainActivity.java and add these two lines below the Activity class declaration. Here we are declaring our VideoView and Media Controller.
public class MainActivity extends AppCompatActivity { VideoView mVideoView; MediaController mediaController;
Now in the onCreate method, we will initialize it like this.
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mediaController = new MediaController(this); mVideoView = findViewById(R.id.mVideoView); }
We must add the video file we want to play to our project.
For this video, we will be using this beautiful video.
Now right, click on the res folder. Then click on new and then click on Android Resource Directory.
Then select raw in the resource type and click on Ok.
A new raw folder will be created as a sub-directory to your res directory.
Right-click on raw and then click Show in Explorer.
Now copy and paste your video here.
So, now coming back to the coding part. It’s time to load the video into our Video View.
Now in onCreate, add these lines of code.
mediaController.setAnchorView(mVideoView); Uri localUri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.mvideo); mVideoView.setVideoURI(localUri); mVideoView.setMediaController(mediaController); mVideoView.start();
Let’s understand the code line by line.
In this line: mediaController.setAnchorView(mVideoView);
We tell our Media Controller or the controller, which controls Play, Pause, Video Progress, etc., to set video view as its anchor view.
In the following line:
Uri localUri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.mvideo);
We are getting the URI ( Unique Location Identifier ) of our video.
And here, we assign that URI to our VideoView. mVideoView.setVideoURI(localUri);
With this line of code, we are assigning our Media Controller to our VideoView.
mVideoView.setMediaController(mediaController);
And finally, we start the video play with this line of code.
mVideoView.start();
Here is what the final code of MainActivity looks like.
public class MainActivity extends AppCompatActivity { VideoView mVideoView; MediaController mediaController; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mediaController = new MediaController(this); mVideoView = findViewById(R.id.mVideoView); mediaController.setAnchorView(mVideoView); Uri localUri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.mvideo); mVideoView.setVideoURI(localUri); mVideoView.setMediaController(mediaController); mVideoView.start(); } }
Run the app by pressing Shift+F10 / Shift + Fn + F10.
Viola! We have the video running. You deserve a pat for making a successful Android Video Player App. 👍👍
Step 4: Loading video through the Internet
You don’t want to load the videos through local files but the web?
Not even a problem.
Let’s do this.
So, first, Open AndroidManifest.xml and then add this permission below the manifest declaration.
<uses-permission android:name="android.permission.INTERNET" />
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.digiwrecks.videoview"> <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher"
Now let’s declare a string and initialize it with our URL.
String url = "https://developers.google.com/training/images/tacoma_narrows.mp4";
Now let’s convert the URL (Uniform Resource Locator) into URI (Uniform Resource Identifier) and assign it to our VideoView.
mVideoView.setVideoURI(Uri.parse(url));
And the rest of the code is the same as we did for the local resource video.
The final code should look like this.
public class MainActivity extends AppCompatActivity { VideoView mVideoView; MediaController mediaController; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mediaController = new MediaController(this); mVideoView = findViewById(R.id.mVideoView); mediaController.setAnchorView(mVideoView); String url = "https://developers.google.com/training/images/tacoma_narrows.mp4"; mVideoView.setVideoURI(Uri.parse(url)); mVideoView.setMediaController(mediaController); mVideoView.start(); } }
Let us run the app and see.
Wow! It’s working. Now your app can stream videos like Netflix and Amazon Prime! Great going.
You can also control the video through the Media Controller, which you can access by tapping on this video.
Now your base app is ready, we will look into some advanced aspects of the Video View widget.
Step 5: Acting on video completion and Showing errors
Ok, so you want to detect and show the completion of the video and the detection of errors?
Well, it’s straightforward.
There are two methods of the VideoView class for it.
These are:
- onCompleteListener
- onErrorListener
Here’s how we can use them.
// implement on completion listener on video view mVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { Toast.makeText(getApplicationContext(), "Thank You...!!!", Toast.LENGTH_LONG).show(); // display a toast when an video is completed } }); mVideoView.setOnErrorListener(new MediaPlayer.OnErrorListener() { @Override public boolean onError(MediaPlayer mp, int what, int extra) { Toast.makeText(getApplicationContext(), "Oops An Error Occurred While Playing Video...!!!", Toast.LENGTH_LONG).show(); // display a toast when an error is occured while playing an video return false; } });
And now you should see the toasts.
Also Read: How to Reset Windows 10 Start Menu to Default Without System Reset
Essential Methods/Functions of VideoView
1. setVideoUri(Uri uri): Set the video’s absolute path to be played.
Return Type: void.
2. start(): Starts the video with the Uri of that Video View object.
Return Type: void.
3. seekTo(int ms): Continue the video from the given millisecond
Return Type: void.
4. pause(): Pauses the video
Return Type – void.
5. resume(): Resumes the video
Return Type – void.
6. stopPlayback(): Stops the playback of the video
Return Type – void.
7. addSubtitleSource(InputStream is, MediaFormat format): Add subtitles to the video through the given format’s input stream.
Return Type – void.
8. setMediaController(MediaController mc): Sets the media controller of the VideoView.
Return type – void.
Also Read: Machine Learning: A Consolidated Way of Implementing Probabilistic Estimates
Listener Methods
1. setOnCompleteListener(MediaPlayer.OnCompleteListener l): Registers a callback to be invoked when the VideoView ends its playback.
Return Type – void.
2. setOnErrorListener(MediaPlayer.OnErrorListener l): Registers a callback to be invoked in case of error during the playback
Return Type – void
3. setOnInfoListener(MediaPlayer.OnInfoListener l): Registers a callback for informational events.
Return Type – void
Informational Methods
1. canPause(): Returns if the video can pause or not
Return Type – Boolean
2. canSeekForward(): Returns if the video view can seek forward or not. In other words, it has reached the end of the video.
Return Type – Boolean
3. canSeekBackward(): Returns if the video view can seek forward or not. Or, in other words, is it just the starting millisecond of the video?
Return Type – Boolean
4. isPlaying(): Returns if the video is playing.
Return Type – Boolean
5. getDuration(): Returns the total duration of the video in milliseconds.
Return type – Boolean
Final Words
This tutorial taught you how to create a simple Android VideoView element application. Following the tutorial, you will create a simple Android application with a functional VideoView element to play videos from a local resource or a URL.