Android VideoView Tutorial with Example Project in Android Studio

0
200

Do you want to work with Videos in your Android application? If yes, then 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 you can 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 connect with us at codeitbro@gmail.com or leave your questions in the comments section, and we will do our best to assist you.

Also ReadAndroid 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. From local resources or the Internet, VideoView can handle multiple format video files with ease.

However, do note that VideoView doesn’t retain its state when a user switches between the apps. For example, you might have noticed that if you close Netflix and open it again after some time, it plays the video right from the position you left.

Well, this isn’t the case with VideoView. To retain states, you will have to explicitly use onSaveInstanceState(Bundle) and onRestoreInstanceState(Bundle).

So let’s get started.

Also ReadAndroid 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.

step 1 - create a new android studio project

You will now see the Android Studio screen, where you will have to select your project template.

To keep things simple, select an Empty Activity and click on the Next button, as shown in the screenshot below.

select a project templateNext, 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 that is unique for every Android application.

videoview app project configuration in android studio

Another important thing to note here is that you can also change the Minimum SDK required for your application to run. Therefore, select that is compatible with most available Android devices.

Once you click on the Finish button, your empty activity of the VideoView application will load. Wait for a few minutes for the Gradle project to build, and once it is done, you can move to the next step.

Also ReadAndroid app to execute code in 23+ programming languages.

Step 2: Adding VideoView to Activity XML

There are two ways of doing this; either you can 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.

adding videoview to activity.xml file

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>

Also ReadReact Native Vs. Ionic Vs. Xamarin Vs. NativeScript; Which One Is Better?

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);

}

Now we need to add the video file that 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.

create an android resource directory

Then select raw in the resource type and click on Ok.

select resource type

A new folder named raw will be created as a sub-directory to your res directory.

Right-click on raw and then click Show in Explorer.

show in explorer - android studio

Now copy and paste your video here.

paste your video resource

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 next 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);

Moving ahead, 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 how 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();
  
   }
}

Now let’s run the app by pressing Shift+F10 / Shift + Fn + F10.

Viola! We have the video running. You deserve a pat on your back for making a successful Android Video Player App. 👍👍

videoview application in action

Also Read10 Best AI Chatbot Apps [2020].

Step 4: Loading video through the Internet

Oh, so 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 like this.

<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 the video like this.

media controller videoview application

Now your base app is ready, and we will look into some advanced aspects of the Video View widget.

Also ReadHow To Market Your App To Boost Your Startup Growth

Step 5: Performing action on video completion and Showing errors

Ok, so you want to detect and show completion of the video and detection of errors?

Well, it’s straightforward.

There are two methods of the VideoView class for it.

These are:

  1. onCompleteListener
  2. 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 ReadHow to Reset Windows 10 Start Menu to Default Without System Reset

Important Methods / Functions of VideoView

1. setVideoUri(Uri uri): To 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 ReadMachine Learning: A Consolidated Way of Implementing Probabilistic Estimates

Listener Methods

1. setOnCompleteListener(MediaPlayer.OnCompleteListener l): Registers a callback to be invoked when the VideoView reaches the end of 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

Also Read6 Best Free Soundboard Software For Windows [2020]

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 or not.

Return Type – Boolean

5. getDuration(): Returns the total duration of the video in milliseconds.

Return type – Boolean

Also ReadHow To Play YouTube Videos in Background on iPhone [2020]

Final Words

In this tutorial, you learned how to use the Android VideoView element by creating a simple application. By following the tutorial, you will create a simple Android application that includes a working VideoView element that can either play video from a local resource or a URL.

Download VideoView Example Project Source Code.