In Focus

Play Video From Internet Using VideoView In Android App

This article shows how to use a VideoView in an Android app to play video files directly from the Web.

Introduction


This article shows how to play videos from URLs directly in our Android Video Player application. Here, we are taking the VideoView control to play the videos. This player includes a media controller that has options to pause, play, rewind, and forward a video.
 
The VideoView class is used to display videos in an Android app. To add media controls to the view, we can use the MediaController class which adds the media controls the UI such as play, pause, rewind, seek, and forward.

Step 1

When we need to play videos in an app, we must set app permissions to use a video from the internet.
 
Add the internet permission in the manifest because our code will play videos from a URL. Now, let us see our mainifest.xml file.
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     xmlns:tools="http://schemas.android.com/tools"  
  4.     package="yourdomain.videoviewexample">  
  5.   
  6.     <uses-permission android:name="android.permission.INTERNET"/>  
  7.   
  8.     <application  
  9.         android:allowBackup="true"  
  10.         android:icon="@mipmap/ic_launcher"  
  11.         android:label="@string/app_name"  
  12.         android:roundIcon="@mipmap/ic_launcher_round"  
  13.         android:supportsRtl="true"  
  14.         android:theme="@style/AppTheme"  
  15.         tools:ignore="GoogleAppIndexingWarning">  
  16.         <activity android:name=".MainActivity">  
  17.             <intent-filter>  
  18.                 <action android:name="android.intent.action.MAIN" />  
  19.   
  20.                 <category android:name="android.intent.category.LAUNCHER" />  
  21.             </intent-filter>  
  22.         </activity>  
  23.     </application>  
  24.   
  25. </manifest>  
Step 2

Define a video view in activity_main.xml and a text that will show the buffering state when there is buffering. We will notify users through this textview. Now, let's replace the code of our file with the one shown below.
  1. <android.support.constraint.ConstraintLayout  
  2.     xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     xmlns:app="http://schemas.android.com/apk/res-auto"  
  4.     xmlns:tools="http://schemas.android.com/tools"  
  5.     android:layout_width="match_parent"  
  6.     android:layout_height="match_parent"  
  7.     >  
  8.   
  9.     <VideoView  
  10.         android:id="@+id/videoview"  
  11.         android:layout_width="0dp"  
  12.         android:layout_height="0dp"  
  13.         android:layout_margin="8dp"  
  14.         app:layout_constraintBottom_toBottomOf="parent"  
  15.         app:layout_constraintDimensionRatio="4:3"  
  16.         app:layout_constraintEnd_toEndOf="parent"  
  17.         app:layout_constraintStart_toStartOf="parent"  
  18.         app:layout_constraintTop_toTopOf="parent"/>  
  19.   
  20.     <TextView  
  21.         android:id="@+id/buffering_textview"  
  22.         android:layout_width="wrap_content"  
  23.         android:layout_height="wrap_content"  
  24.         android:layout_margin="8dp"  
  25.         android:text="@string/buffering_string"  
  26.         android:textSize="18sp"  
  27.         android:textStyle="bold"  
  28.         android:textColor="@android:color/white"  
  29.         app:layout_constraintBottom_toBottomOf="parent"  
  30.         app:layout_constraintEnd_toEndOf="parent"  
  31.         app:layout_constraintStart_toStartOf="parent"  
  32.         app:layout_constraintTop_toTopOf="parent"/>  
  33.   
  34. </android.support.constraint.ConstraintLayout>  
Here, we are using ConstraintLayot but you can use RelativeLayout as well. Now, find these views in an activity called MainActivity.java

Step 3 

In our MainActivity.java, find the views in onCreate() method as shown below and intialize the videoview.
  1. import android.media.MediaPlayer;  
  2. import android.net.Uri;  
  3. import android.os.Build;  
  4. import android.support.v7.app.AppCompatActivity;  
  5. import android.os.Bundle;  
  6. import android.webkit.URLUtil;  
  7. import android.widget.MediaController;  
  8. import android.widget.TextView;  
  9. import android.widget.Toast;  
  10. import android.widget.VideoView;  
  11.   
  12. public class MainActivity extends AppCompatActivity {  
  13.   
  14.     private static final String VIDEO_SAMPLE =  
  15.             "https://developers.google.com/training/images/tacoma_narrows.mp4";  
  16.   
  17.     private VideoView mVideoView;  
  18.     private TextView mBufferingTextView;  
  19.   
  20.     // Current playback position (in milliseconds).  
  21.     private int mCurrentPosition = 0;  
  22.   
  23.     // Tag for the instance state bundle.  
  24.     private static final String PLAYBACK_TIME = "play_time";  
  25.   
  26.     @Override  
  27.     protected void onCreate(Bundle savedInstanceState) {  
  28.         super.onCreate(savedInstanceState);  
  29.         setContentView(R.layout.activity_main);  
  30.   
  31.         mVideoView = findViewById(R.id.videoview);  
  32.         mBufferingTextView = findViewById(R.id.buffering_textview);  
  33.   
  34.         if (savedInstanceState != null) {  
  35.             mCurrentPosition = savedInstanceState.getInt(PLAYBACK_TIME);  
  36.         }  
  37.   
  38.         // Set up the media controller widget and attach it to the video view.  
  39.         MediaController controller = new MediaController(this);  
  40.         controller.setMediaPlayer(mVideoView);  
  41.         mVideoView.setMediaController(controller);  
  42.     }  
  43.   
  44.   
  45.     @Override  
  46.     protected void onStart() {  
  47.         super.onStart();  
  48.   
  49.         // Load the media each time onStart() is called.  
  50.         initializePlayer();  
  51.     }  
  52.   
  53.     @Override  
  54.     protected void onPause() {  
  55.         super.onPause();  
  56.   
  57.         // In Android versions less than N (7.0, API 24), onPause() is the  
  58.         // end of the visual lifecycle of the app.  Pausing the video here  
  59.         // prevents the sound from continuing to play even after the app  
  60.         // disappears.  
  61.         //  
  62.         // This is not a problem for more recent versions of Android because  
  63.         // onStop() is now the end of the visual lifecycle, and that is where  
  64.         // most of the app teardown should take place.  
  65.         if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {  
  66.             mVideoView.pause();  
  67.         }  
  68.     }  
  69.   
  70.     @Override  
  71.     protected void onStop() {  
  72.         super.onStop();  
  73.   
  74.         // Media playback takes a lot of resources, so everything should be  
  75.         // stopped and released at this time.  
  76.         releasePlayer();  
  77.     }  
  78.   
  79.     @Override  
  80.     protected void onSaveInstanceState(Bundle outState) {  
  81.         super.onSaveInstanceState(outState);  
  82.   
  83.         // Save the current playback position (in milliseconds) to the  
  84.         // instance state bundle.  
  85.         outState.putInt(PLAYBACK_TIME, mVideoView.getCurrentPosition());  
  86.     }  
  87.   
  88.     private void initializePlayer() {  
  89.         // Show the "Buffering..." message while the video loads.  
  90.         mBufferingTextView.setVisibility(VideoView.VISIBLE);  
  91.   
  92.         // Buffer and decode the video sample.  
  93.         Uri videoUri = getMedia(VIDEO_SAMPLE);  
  94.         mVideoView.setVideoURI(videoUri);  
  95.   
  96.         // Listener for onPrepared() event (runs after the media is prepared).  
  97.         mVideoView.setOnPreparedListener(  
  98.                 new MediaPlayer.OnPreparedListener() {  
  99.                     @Override  
  100.                     public void onPrepared(MediaPlayer mediaPlayer) {  
  101.   
  102.                         // Hide buffering message.  
  103.                         mBufferingTextView.setVisibility(VideoView.INVISIBLE);  
  104.   
  105.                         // Restore saved position, if available.  
  106.                         if (mCurrentPosition > 0) {  
  107.                             mVideoView.seekTo(mCurrentPosition);  
  108.                         } else {  
  109.                             // Skipping to 1 shows the first frame of the video.  
  110.                             mVideoView.seekTo(1);  
  111.                         }  
  112.   
  113.                         // Start playing!  
  114.                         mVideoView.start();  
  115.                     }  
  116.                 });  
  117.   
  118.         // Listener for onCompletion() event (runs after media has finished  
  119.         // playing).  
  120.         mVideoView.setOnCompletionListener(  
  121.                 new MediaPlayer.OnCompletionListener() {  
  122.                     @Override  
  123.                     public void onCompletion(MediaPlayer mediaPlayer) {  
  124.                         Toast.makeText(MainActivity.this,  
  125.                                 R.string.toast_message,  
  126.                                 Toast.LENGTH_SHORT).show();  
  127.   
  128.                         // Return the video position to the start.  
  129.                         mVideoView.seekTo(0);  
  130.                     }  
  131.                 });  
  132.     }  
  133.   
  134.   
  135.     // Release all media-related resources. In a more complicated app this  
  136.     // might involve unregistering listeners or releasing audio focus.  
  137.     private void releasePlayer() {  
  138.         mVideoView.stopPlayback();  
  139.     }  
  140.   
  141.     // Get a Uri for the media sample regardless of whether that sample is  
  142.     // embedded in the app resources or available on the internet.  
  143.     private Uri getMedia(String mediaName) {  
  144.         if (URLUtil.isValidUrl(mediaName)) {  
  145.             // Media name is an external URL.  
  146.             return Uri.parse(mediaName);  
  147.         } else {  
  148.   
  149.             // you can also put a video file in raw package and get file from there as shown below  
  150.   
  151.             return Uri.parse("android.resource://" + getPackageName() +  
  152.                     "/raw/" + mediaName);  
  153.   
  154.   
  155.         }  
  156.     }  
  157.   
  158. }  
Now, you need to implement all methods for activities like onStart(), onPause(), onStop(). These methods will be executed when the Start, Pause, and Stop buttons are clicked on the controller.
 
The getMedia() method returns the URI of the video. If you want to play form local storage then put a file in the raw directory and write the below code.
  1. return Uri.parse("android.resource://" + getPackageName() +  
  2.                   "/raw/" + mediaName);  
Now, path here is a raw directory; simply put your media file name instead of mediaName like samplVideo.mp4 and something else.

When you play a video in an app on your phone, the Internet might be slow and buffering may occur.
 
The last thing we want to do is, on the onCompletion() method, we show a toast when the video is finished playing.
 
Output 
 
Below screenshots are from my phone. 

First, it shows buffering because it takes some time for the URL to load on VideoView.

 
Now here, the player is in the initialization state. Let us see the second one to visualize the video with media controls.


Now after completion, we are showing a toast message. See the completed state in the below picture.

Conclusion


In this article, we have learned how to play videos in an Android app directly from the internet.