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.
Add the internet permission in the manifest because our code will play videos from a URL. Now, let us see our mainifest.xml file.
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- package="yourdomain.videoviewexample">
- <uses-permission android:name="android.permission.INTERNET"/>
- <application
- android:allowBackup="true"
- android:icon="@mipmap/ic_launcher"
- android:label="@string/app_name"
- android:roundIcon="@mipmap/ic_launcher_round"
- android:supportsRtl="true"
- android:theme="@style/AppTheme"
- tools:ignore="GoogleAppIndexingWarning">
- <activity android:name=".MainActivity">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- </application>
- </manifest>
- <android.support.constraint.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"
- >
- <VideoView
- android:id="@+id/videoview"
- android:layout_width="0dp"
- android:layout_height="0dp"
- android:layout_margin="8dp"
- app:layout_constraintBottom_toBottomOf="parent"
- app:layout_constraintDimensionRatio="4:3"
- app:layout_constraintEnd_toEndOf="parent"
- app:layout_constraintStart_toStartOf="parent"
- app:layout_constraintTop_toTopOf="parent"/>
- <TextView
- android:id="@+id/buffering_textview"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_margin="8dp"
- android:text="@string/buffering_string"
- android:textSize="18sp"
- android:textStyle="bold"
- android:textColor="@android:color/white"
- app:layout_constraintBottom_toBottomOf="parent"
- app:layout_constraintEnd_toEndOf="parent"
- app:layout_constraintStart_toStartOf="parent"
- app:layout_constraintTop_toTopOf="parent"/>
- </android.support.constraint.ConstraintLayout>
- import android.media.MediaPlayer;
- import android.net.Uri;
- import android.os.Build;
- import android.support.v7.app.AppCompatActivity;
- import android.os.Bundle;
- import android.webkit.URLUtil;
- import android.widget.MediaController;
- import android.widget.TextView;
- import android.widget.Toast;
- import android.widget.VideoView;
- public class MainActivity extends AppCompatActivity {
- private static final String VIDEO_SAMPLE =
- "https://developers.google.com/training/images/tacoma_narrows.mp4";
- private VideoView mVideoView;
- private TextView mBufferingTextView;
- // Current playback position (in milliseconds).
- private int mCurrentPosition = 0;
- // Tag for the instance state bundle.
- private static final String PLAYBACK_TIME = "play_time";
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- mVideoView = findViewById(R.id.videoview);
- mBufferingTextView = findViewById(R.id.buffering_textview);
- if (savedInstanceState != null) {
- mCurrentPosition = savedInstanceState.getInt(PLAYBACK_TIME);
- }
- // Set up the media controller widget and attach it to the video view.
- MediaController controller = new MediaController(this);
- controller.setMediaPlayer(mVideoView);
- mVideoView.setMediaController(controller);
- }
- @Override
- protected void onStart() {
- super.onStart();
- // Load the media each time onStart() is called.
- initializePlayer();
- }
- @Override
- protected void onPause() {
- super.onPause();
- // In Android versions less than N (7.0, API 24), onPause() is the
- // end of the visual lifecycle of the app. Pausing the video here
- // prevents the sound from continuing to play even after the app
- // disappears.
- //
- // This is not a problem for more recent versions of Android because
- // onStop() is now the end of the visual lifecycle, and that is where
- // most of the app teardown should take place.
- if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
- mVideoView.pause();
- }
- }
- @Override
- protected void onStop() {
- super.onStop();
- // Media playback takes a lot of resources, so everything should be
- // stopped and released at this time.
- releasePlayer();
- }
- @Override
- protected void onSaveInstanceState(Bundle outState) {
- super.onSaveInstanceState(outState);
- // Save the current playback position (in milliseconds) to the
- // instance state bundle.
- outState.putInt(PLAYBACK_TIME, mVideoView.getCurrentPosition());
- }
- private void initializePlayer() {
- // Show the "Buffering..." message while the video loads.
- mBufferingTextView.setVisibility(VideoView.VISIBLE);
- // Buffer and decode the video sample.
- Uri videoUri = getMedia(VIDEO_SAMPLE);
- mVideoView.setVideoURI(videoUri);
- // Listener for onPrepared() event (runs after the media is prepared).
- mVideoView.setOnPreparedListener(
- new MediaPlayer.OnPreparedListener() {
- @Override
- public void onPrepared(MediaPlayer mediaPlayer) {
- // Hide buffering message.
- mBufferingTextView.setVisibility(VideoView.INVISIBLE);
- // Restore saved position, if available.
- if (mCurrentPosition > 0) {
- mVideoView.seekTo(mCurrentPosition);
- } else {
- // Skipping to 1 shows the first frame of the video.
- mVideoView.seekTo(1);
- }
- // Start playing!
- mVideoView.start();
- }
- });
- // Listener for onCompletion() event (runs after media has finished
- // playing).
- mVideoView.setOnCompletionListener(
- new MediaPlayer.OnCompletionListener() {
- @Override
- public void onCompletion(MediaPlayer mediaPlayer) {
- Toast.makeText(MainActivity.this,
- R.string.toast_message,
- Toast.LENGTH_SHORT).show();
- // Return the video position to the start.
- mVideoView.seekTo(0);
- }
- });
- }
- // Release all media-related resources. In a more complicated app this
- // might involve unregistering listeners or releasing audio focus.
- private void releasePlayer() {
- mVideoView.stopPlayback();
- }
- // Get a Uri for the media sample regardless of whether that sample is
- // embedded in the app resources or available on the internet.
- private Uri getMedia(String mediaName) {
- if (URLUtil.isValidUrl(mediaName)) {
- // Media name is an external URL.
- return Uri.parse(mediaName);
- } else {
- // you can also put a video file in raw package and get file from there as shown below
- return Uri.parse("android.resource://" + getPackageName() +
- "/raw/" + mediaName);
- }
- }
- }
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.
- return Uri.parse("android.resource://" + getPackageName() +
- "/raw/" + mediaName);
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.
In this article, we have learned how to play videos in an Android app directly from the internet.




റ്റിജു മുളമൂട്ടിൽPosted May 7, 2019, 8:15 AM
Want to add media player on my food delivering wat i hav to do my whatsapp no +96599403882
Arvind SinghPosted Feb 10, 2019, 11:01 PM
Nice article...