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. <uses-permission android:name="android.permission.INTERNET"/>
  6. <application
  7. android:allowBackup="true"
  8. android:icon="@mipmap/ic_launcher"
  9. android:label="@string/app_name"
  10. android:roundIcon="@mipmap/ic_launcher_round"
  11. android:supportsRtl="true"
  12. android:theme="@style/AppTheme"
  13. tools:ignore="GoogleAppIndexingWarning">
  14. <activity android:name=".MainActivity">
  15. <intent-filter>
  16. <action android:name="android.intent.action.MAIN" />
  17. <category android:name="android.intent.category.LAUNCHER" />
  18. </intent-filter>
  19. </activity>
  20. </application>
  21. </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. <VideoView
  9. android:id="@+id/videoview"
  10. android:layout_width="0dp"
  11. android:layout_height="0dp"
  12. android:layout_margin="8dp"
  13. app:layout_constraintBottom_toBottomOf="parent"
  14. app:layout_constraintDimensionRatio="4:3"
  15. app:layout_constraintEnd_toEndOf="parent"
  16. app:layout_constraintStart_toStartOf="parent"
  17. app:layout_constraintTop_toTopOf="parent"/>
  18. <TextView
  19. android:id="@+id/buffering_textview"
  20. android:layout_width="wrap_content"
  21. android:layout_height="wrap_content"
  22. android:layout_margin="8dp"
  23. android:text="@string/buffering_string"
  24. android:textSize="18sp"
  25. android:textStyle="bold"
  26. android:textColor="@android:color/white"
  27. app:layout_constraintBottom_toBottomOf="parent"
  28. app:layout_constraintEnd_toEndOf="parent"
  29. app:layout_constraintStart_toStartOf="parent"
  30. app:layout_constraintTop_toTopOf="parent"/>
  31. </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. public class MainActivity extends AppCompatActivity {
  12. private static final String VIDEO_SAMPLE =
  13. "https://developers.google.com/training/images/tacoma_narrows.mp4";
  14. private VideoView mVideoView;
  15. private TextView mBufferingTextView;
  16. // Current playback position (in milliseconds).
  17. private int mCurrentPosition = 0;
  18. // Tag for the instance state bundle.
  19. private static final String PLAYBACK_TIME = "play_time";
  20. @Override
  21. protected void onCreate(Bundle savedInstanceState) {
  22. super.onCreate(savedInstanceState);
  23. setContentView(R.layout.activity_main);
  24. mVideoView = findViewById(R.id.videoview);
  25. mBufferingTextView = findViewById(R.id.buffering_textview);
  26. if (savedInstanceState != null) {
  27. mCurrentPosition = savedInstanceState.getInt(PLAYBACK_TIME);
  28. }
  29. // Set up the media controller widget and attach it to the video view.
  30. MediaController controller = new MediaController(this);
  31. controller.setMediaPlayer(mVideoView);
  32. mVideoView.setMediaController(controller);
  33. }
  34. @Override
  35. protected void onStart() {
  36. super.onStart();
  37. // Load the media each time onStart() is called.
  38. initializePlayer();
  39. }
  40. @Override
  41. protected void onPause() {
  42. super.onPause();
  43. // In Android versions less than N (7.0, API 24), onPause() is the
  44. // end of the visual lifecycle of the app. Pausing the video here
  45. // prevents the sound from continuing to play even after the app
  46. // disappears.
  47. //
  48. // This is not a problem for more recent versions of Android because
  49. // onStop() is now the end of the visual lifecycle, and that is where
  50. // most of the app teardown should take place.
  51. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
  52. mVideoView.pause();
  53. }
  54. }
  55. @Override
  56. protected void onStop() {
  57. super.onStop();
  58. // Media playback takes a lot of resources, so everything should be
  59. // stopped and released at this time.
  60. releasePlayer();
  61. }
  62. @Override
  63. protected void onSaveInstanceState(Bundle outState) {
  64. super.onSaveInstanceState(outState);
  65. // Save the current playback position (in milliseconds) to the
  66. // instance state bundle.
  67. outState.putInt(PLAYBACK_TIME, mVideoView.getCurrentPosition());
  68. }
  69. private void initializePlayer() {
  70. // Show the "Buffering..." message while the video loads.
  71. mBufferingTextView.setVisibility(VideoView.VISIBLE);
  72. // Buffer and decode the video sample.
  73. Uri videoUri = getMedia(VIDEO_SAMPLE);
  74. mVideoView.setVideoURI(videoUri);
  75. // Listener for onPrepared() event (runs after the media is prepared).
  76. mVideoView.setOnPreparedListener(
  77. new MediaPlayer.OnPreparedListener() {
  78. @Override
  79. public void onPrepared(MediaPlayer mediaPlayer) {
  80. // Hide buffering message.
  81. mBufferingTextView.setVisibility(VideoView.INVISIBLE);
  82. // Restore saved position, if available.
  83. if (mCurrentPosition > 0) {
  84. mVideoView.seekTo(mCurrentPosition);
  85. } else {
  86. // Skipping to 1 shows the first frame of the video.
  87. mVideoView.seekTo(1);
  88. }
  89. // Start playing!
  90. mVideoView.start();
  91. }
  92. });
  93. // Listener for onCompletion() event (runs after media has finished
  94. // playing).
  95. mVideoView.setOnCompletionListener(
  96. new MediaPlayer.OnCompletionListener() {
  97. @Override
  98. public void onCompletion(MediaPlayer mediaPlayer) {
  99. Toast.makeText(MainActivity.this,
  100. R.string.toast_message,
  101. Toast.LENGTH_SHORT).show();
  102. // Return the video position to the start.
  103. mVideoView.seekTo(0);
  104. }
  105. });
  106. }
  107. // Release all media-related resources. In a more complicated app this
  108. // might involve unregistering listeners or releasing audio focus.
  109. private void releasePlayer() {
  110. mVideoView.stopPlayback();
  111. }
  112. // Get a Uri for the media sample regardless of whether that sample is
  113. // embedded in the app resources or available on the internet.
  114. private Uri getMedia(String mediaName) {
  115. if (URLUtil.isValidUrl(mediaName)) {
  116. // Media name is an external URL.
  117. return Uri.parse(mediaName);
  118. } else {
  119. // you can also put a video file in raw package and get file from there as shown below
  120. return Uri.parse("android.resource://" + getPackageName() +
  121. "/raw/" + mediaName);
  122. }
  123. }
  124. }
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.