Search results for

All search results
Best daily deals

Affiliate links on Android Authority may earn us a commission. Learn more.

Display YouTube, Vimeo, and Dailymotion videos in your Android apps

Deliver a richer, multimedia experience, by embedding videos in your application's "res" directory, or streaming them directly from YouTube, Video, Dailymotion and more.
By

Published onFebruary 9, 2019

If your latest Android app is going to find an audience, then you need to deliver an engaging user experience.

In this article, I’ll show you how to deliver a richer, multimedia experience, by incorporating video content into your Android apps.

We’ll be exploring the two major ways that you can add videos to your applications:

  • Including one or more video files in your project’s “resources” directory.
  • Embedding content from a video-sharing website.

When you think about online videos, YouTube is probably the first thing that springs to mind – but YouTube isn’t the only video-sharing platform out there! To ensure you have as many options as possible, we’ll be covering three different ways that you can embed online videos, from three different video-sharing platforms.

By the end of this article, you’ll know how to stream content from:

  • YouTube, using the YouTube Android Player API.
  • Dailymotion, using the Dailymotion Player SDK for Android.
  • Vimeo, using Android’s built-in WebView component.

Although we’ll be sticking to YouTube, Dailymotion and Vimeo, you should be able to embed content from any video-sharing platform, using the platform’s own API or SDK, or Android’s WebView component. Just because your favorite video-sharing website isn’t included in this list, doesn’t mean you can’t use the techniques discussed in this article!

Playing a video with VideoView

By adding a video to your application’s “res” directory, you can guarantee this video will always be accessible, regardless of whether the user has an active Internet connection. You should consider bundling a video with your application files, if the video in question is required to deliver a good user experience, or it provides part of your app’s core functionality.

Distributing videos as part of your application will also spare your users the overheads associated with downloading and buffering a video from the Internet, helping to preserve their device’s battery and data allowance.

Just be aware that adding video files to your application will affect the size of your APK, so you should take extra precautions to ensure your APK doesn’t get out of control.

Displaying local videos, with VideoView

In this section, we’ll create an application that displays a video clip, which is stored locally in our application’s “res” directory.

We’ll display this video using Android’s VideoView class, and provide the user with a set of media controls, via Android’s MediaController class. The MediaController class includes play, pause, rewind and fast-forward controls, plus a progress slider that’ll allow the user to skip to a specific point within the video.

Getting started: Creating a “raw” directory

You’ll need to add the video file to your application’s “res/raw” directory. Android projects don’t contain this directory by default, so let’s create it now:

  • Control-click your project’s “res” folder and select “New > Android Resource Directory.”
  • In the subsequent window, open the “Resource type” dropdown and select “raw.”
  • The “Directory name” should update to “raw” automatically, but if it doesn’t then you’ll need to rename it manually.
  • Click “OK.”

Android supports a range of video formats; you can either use one of your own videos or download a compatible video from a website that offers free stock footage, such as Sample Videos.

Once you have a video file, add it to your application by dragging and dropping it into the “raw” directory.

Add a VideoView to your UI

Next, we need to add a VideoView to our application’s user interface. This VideoView widget implements much of the basic behavior required to play a video.

In our VideoView widget, I’m setting both “layout_width” and “layout_height” to 0dp, as this allows the size of the VideoView to be calculated dynamically, based on the dimensions of the video we want it to display.

Code
<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"
   tools:context=".MainActivity">

  <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"/>

</android.support.constraint.ConstraintLayout>

Loading and playing a video programmatically

Now, we need to retrieve the path to our local video; play the clip automatically at startup, and give the user a way to interact with the video.

1. Retrieve the video file

Open your project’s MainActivity class, and add a constant to represent the video file:

Code
private static final String VIDEO = "samplevideo";

Next, define the URI that our VideoView widget should play, using the getMedia() and setVideoUri() methods:

Code
private void initializePlayer() {
       Uri videoUri = getMedia(VIDEO);
       videoView.setVideoURI(videoUri);

                   }

We then need to create a getMedia() method that takes the name of the video file, in the form of a string, and then converts it into a URI object representing the path to this file:

Code
private Uri getMedia(String mediaName) {
      if (URLUtil.isValidUrl(mediaName)) {
           return Uri.parse(mediaName);

Note that the string and returned URI don’t include the video’s extension.

2. Play the video

Next, we load the video each time onStart() is called, and set the video playing automatically, using the start() method:

Code
@Override
   protected void onStart() {
       super.onStart();
       initializePlayer();
       videoView.start();
   }

3. Cleaning up

Playing a video puts significant strain on the system, so it’s important to release all the resources held by VideoView, as soon as they’re no longer required.

Since our app is fairly straightforward, we just need to stop the video and release all of its resources, but in more complicated applications this step might involve unregistering multiple listeners.

I’m going to create a releasePlayer() method, and call the stopPlayback() method on the VideoView:

Code
private void releasePlayer() {
       videoView.stopPlayback();
   }

We can then override the onStop() method and call releasePlayer():

Code
@Override
   protected void onStop() {
       super.onStop();
       releasePlayer();
   }

Next, we need to tackle Android’s onPause() method.

Prior to Android 7.0, onPause() marked the end of the visual lifecycle, so you could start releasing resources as soon as your application entered a paused state. However, with the introduction of multi-window and picture-in-picture mode in Android 7.0, it’s possible for a paused application to remain visible onscreen, so you may need to continue playing the video, even when it’s in a paused state.

To ensure our app behaves correctly across all versions of Android, we need to perform a version check and only pause VideoView in onPause() when our application is installed on Android Marshmallow or earlier.

Code
@Override
   protected void onPause() {
       super.onPause();
       if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
           videoView.pause();
       }
   }

4. Add playback controls

Currently, there’s no way for the user to pause, rewind or otherwise interact with the video, so we need to add some media controls, using Android’s MediaController class.

In the following snippet, we’re instantiating a MediaController programmatically, and then attaching it to our VideoView using setMediaPlayer(). Finally, we’re informing the VideoView about the new MediaController, using the setMediaController() method:

Code
MediaController controller = new MediaController(this);
      controller.setMediaPlayer(videoView);
      videoView.setMediaController(controller);
   }

ViewView and MediaController: Completed code

After adding all the above to our MainActivity, your code should look something like this:

Code
import android.support.v7.app.AppCompatActivity;
import android.os.Build;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;
import android.net.Uri;
import android.webkit.URLUtil;

public class MainActivity extends AppCompatActivity {

   private static final String VIDEO = "samplevideo";

//Add a constant for the video file//

   private VideoView videoView;
   private int currentPosition = 0;

   private static final String PLAYBACK = "playback";

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       videoView = findViewById(R.id.videoView);

       if (savedInstanceState != null) {
           currentPosition = savedInstanceState.getInt(PLAYBACK);
       }

//Create a MediaController object//

       MediaController controller = new MediaController(this);

//Attach the media controller to your VideoView//

       controller.setMediaPlayer(videoView);

//Notify the VideoView about its assigned MediaController//

       videoView.setMediaController(controller);
   }

   @Override
   protected void onStart() {
       super.onStart();

//Load the media every time onStart() is called//

       initializePlayer();

//Start playing the video//

       videoView.start();
   }

   @Override
   protected void onPause() {
       super.onPause();

//If our app is on running on API level 23 or lower….//

       if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {

//...then pause the video whenever onPause() is called//

           videoView.pause();
       }
   }

   @Override
   protected void onStop() {
       super.onStop();

//Stop the video and release all resources held by the VideoView//

       releasePlayer();
   }

//Create an initializePlayer() method//

   private void initializePlayer() {

//Set the URI that the VideoView should play//

       Uri videoUri = getMedia(VIDEO);
       videoView.setVideoURI(videoUri);

                   }

//Release all resources//

   private void releasePlayer() {
       videoView.stopPlayback();
   }

//Retrieve the video file and convert it into a URI//

   private Uri getMedia(String mediaName) {
       if (URLUtil.isValidUrl(mediaName)) {
           return Uri.parse(mediaName);
       } else {
           return Uri.parse("android.resource://" + getPackageName() +
                   "/raw/" + mediaName);
       }
   }
}

Testing your VideoView project

Install this project on your Android smartphone, tablet or Android Virtual Device (AVD). The video clip will start playing as soon as the application launches, but you can also control the video by tapping the VideoView widget, which reveals a set of media controls.

Once the MediaController is visible onscreen, you can play, pause, rewind and fast-forward the video, and jump to any point within the clip by dragging the MediaController’s progress bar.

How to embed YouTube videos in your Android app

Embedding a video file within your application is a great way to ensure that video is always available, regardless of the device’s Internet connection. However, embedding multiple large, high-resolution videos in your app is also a great way to increase the size of your APK!

If you’re concerned about APK size, or your application includes videos that are nice-to-have added extras, then you may want to publish those videos to an online platform and then stream them through your application at runtime.

When it comes to publishing videos online, there’s one website that instantly springs to mind, so in this section I’ll show you how to embed any YouTube video in your app, using the YouTube Android Player API client library.

Retrieving a YouTube video’s ID

To start, you need to decide which YouTube video you want to display, and then retrieve its unique video ID.

You can use any YouTube video but I’m opting for “Android Authority’s Favorite Tech of 2018.” Load your chosen video and take a look at its URL in your browser’s address bar, for example the URL for the Android Authority video is:

youtube.com/watch?v=hJLBcViaX8Q

The ID is the part of the URL that uniquely identifies this video, which is the string of characters at the end of the URL (basically, everything after the “=” symbol). The video ID for the Android Authority video is:

hJLBcViaX8Q

Make a note of your video’s ID, as we’ll be using this later.

Get your project’s SHA-1 fingerprint

In order to access the YouTube Android Player API, you’ll need to generate an API key with Android restrictions. This involves linking the API key to your project’s unique package name and certificate fingerprint (SHA-1).

You can retrieve your project’s SHA-1 fingerprint, via the Gradle Console:

  • Select the Gradle tab along the right-hand side of the Android Studio window.
  • Select the “app” module, followed by “Tasks >Android > signingReport.”
  • Open the Gradle Console tab that appears towards the bottom-right of the screen.
  • The Gradle Console will open automatically. Find the SHA-1 value in this window, and make a note of it.

We’re using a debug certificate fingerprint, which is only suitable for testing an application. Before publishing an app, you should always generate a new API key based on that application’s release certificate.

Register with the Google API Console

Before you can use the YouTube Android Player API, you need to register your application in the Google API Console:

  • Head over to the API Console.
    In the header, select the name of your current project (where the cursor is positioned in the following screenshot).
  • In the subsequent window, select “New project.”
  • Give your project a name, and then click “Create.”
  • In the left-hand menu, select “Credentials.”
  • Give the blue “Create credentials” button a click, and then select “API key.”
  • Your API key will now appear in a popup, which includes a prompt to restrict this API key. Restricted keys are more secure, so unless you specifically require an unrestricted API key, opt to “Restrict key.”
  • On the subsequent screen, give your API key a distinctive name.
  • Select the “Android apps” radio button.
  • Click “Add package name and fingerprint.”
  • Copy/paste your project’s SHA-1 fingerprint into the subsequent section, and then enter your project’s package name (which appears at the top of every Java class file and in your project’s Manifest).
  • When you’re happy with the information you’ve entered, click “Save.”

Download the YouTube Android Player API

Next, you’ll need to download the YouTube Android Player API client library. When using this library, it’s recommended that you enable ProGuard, to help keep your APK as lightweight as possible.

To add the YouTube library to your project:

  • Head over to the YouTube Android Player website, and download the latest version.
  • Unzip the subsequent zip file.
  • Open the newly-unzipped folder and navigate to its “libs” subfolder – it should contain a “YouTubeAndroidPlayerApi.jar” file.
  • In Android Studio, switch to the “Project” view.
  • To ensure the YouTube library is included in your build path, you’ll need to import the .jar into your project’s “<project_root>/libs” directory. Open your project’s “app/libs” folder, and then drag and drop the .jar into position.
  • Open your build.gradle file and add the YouTube library as a project dependency:
Code
dependencies {
   implementation fileTree(dir: 'libs', include: ['*.jar'])
   implementation 'com.android.support:appcompat-v7:28.0.0'
   implementation 'com.android.support:design:28.0.0'
   implementation 'com.android.support.constraint:constraint-layout:1.1.3'
   testImplementation 'junit:junit:4.12'
   androidTestImplementation 'com.android.support.test:runner:1.0.2'

//Add the following//

   implementation files('libs/YouTubeAndroidPlayerApi.jar')
}
  • When prompted, sync your Gradle files.

Update your Manifest

If your application is going to display any online video content, then it’ll need access to the Internet.

Open your project’s Manifest and add the Internet permission:

Code
<uses-permission android:name="android.permission.INTERNET" />

To give the user a taste of that cinematic, widescreen experience, I’m also setting MainActivity to launch in landscape mode:

Code
<activity android:name=".MainActivity"
       android:screenOrientation="landscape">

       <intent-filter>
           <action android:name="android.intent.action.MAIN" />

           <category android:name="android.intent.category.LAUNCHER" />
       </intent-filter>
    </activity>
</application>

Building the YouTube Player layout

You can display a YouTube video, using either:

  • YouTubePlayerView. If you want to use YouTubePlayerView in your layout, then you’ll need to extend YouTubeBaseActivity in that layout’s corresponding Activity class.
  • YouTubePlayerFragment. This is a fragment that contains a YouTubePlayerView. If you choose to implement a YouTubePlayerFragment, then you won’t have to extend from YouTubeBaseActivity.

I’ll be using YouTubePlayerView, so open your project’s “activity_main.xml” file, and add a YouTubePlayerView widget:

Code
<?xml version="1.0" encoding="utf-8"?>
<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"
   tools:context=".MainActivity">

   <com.google.android.youtube.player.YouTubePlayerView
       android:id="@+id/YouTubePlayer"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_marginTop="8dp"
       android:layout_marginBottom="8dp"
       app:layout_constraintBottom_toBottomOf="parent"
       app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

Implementing the YouTube Player

Next, open your MainActivity and complete the following tasks:

1. Extend YouTubeBaseActivity

Since we’re using a YouTubePlayerView in our layout, we need to extend YouTubeBaseActivity:

Code
public class MainActivity extends YouTubeBaseActivity {

2. Initialize YouTube Player

We initialize the YouTube Player by calling initialize() and passing the API key we created earlier:

Code
YouTubePlayerView youTubePlayerView =
       (YouTubePlayerView) findViewById(R.id.YouTubePlayer);

youTubePlayerView.initialize(YOUR_API_KEY,
       new YouTubePlayer.OnInitializedListener() {

3. Implement onInitializationSuccess and onInitializationFailure

Finally, we need to specify how our application should react, depending on whether the initialization is a success, or a failure. If the YouTube Player is initialized successfully, then we can load our video, by passing the unique video ID:

Code
public void onInitializationSuccess(YouTubePlayer.Provider provider,
                        YouTubePlayer youTubePlayer, boolean b) {

//Specify the video ID//

   youTubePlayer.loadVideo("hJLBcViaX8Q");

Next, we need to tell our application how it should handle failed initializations. I’m going to display a Toast:

Code
public void onInitializationFailure(YouTubePlayer.Provider provider,
                                  YouTubeInitializationResult youTubeInitializationResult) {
                   Toast.makeText(MainActivity.this, "An error occurred", Toast.LENGTH_SHORT).show();
          }

Playing a YouTube video: Completed code

Add all the above to your MainActivity, and you should end up with something like this:

Code
import android.os.Bundle;
import android.widget.Toast;

import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;

//Extend YouTubeBaseActivity//

public class MainActivity extends YouTubeBaseActivity {

//Don’t forget to replace this with your own unique API key//

   public static final String YOUR_API_KEY = "YOUR_API_KEY_HERE";

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);

       YouTubePlayerView youTubePlayerView =
               (YouTubePlayerView) findViewById(R.id.YouTubePlayer);

//Initialize the YouTube Player//

       youTubePlayerView.initialize(YOUR_API_KEY,
               new YouTubePlayer.OnInitializedListener() {
                   @Override

//If the YouTube Player is initialized successfully...//

                   public void onInitializationSuccess(YouTubePlayer.Provider provider,
                                           YouTubePlayer youTubePlayer, boolean b) {

//..then start playing the following video//

                       youTubePlayer.loadVideo("hJLBcViaX8Q");

                   }
                   @Override

//If the initialization fails...//

                   public void onInitializationFailure(YouTubePlayer.Provider provider,
                                           YouTubeInitializationResult youTubeInitializationResult) {

//...then display a toast//

                       Toast.makeText(MainActivity.this, "An error occurred", Toast.LENGTH_SHORT).show();
                   }
               });
   }
}

Testing the YouTube Android Player API

You can test this application on either a physical Android smartphone or tablet, or an AVD. If you’re using an AVD, then make sure you’re using a system image that includes Google Play services. The YouTube app must also be installed on the AVD or physical Android device, as the YouTube API relies on a service that’s distributed as part of the YouTube for Android app.

Install the project on your device, and the YouTube video should start playing automatically, as soon as the application loads. If you tap the video, then you’ll have access to all the familiar YouTube controls that you can use to pause, play, fast-forward and rewind the video.

Display Dailymotion content in a WebView

When it comes to embedding videos in your Android app, there’s a wide range of video-sharing platforms that you can choose from, and some platforms have even produced SDKs dedicated to helping you interact with their content – including Dailymotion.

The Dailymotion Player SDK for Android provides a thin wrapper around Android’s WebView component, that makes it easier to embed Dailymotion videos in your applications.

In this section, I’ll show you how to stream any video from the Dailymotion website, using the third party Dailymotion Player SDK.

Get the Dailymotion video ID

Firstly, head over to Dailymotion, find a video that you want to display, and then retrieve its video ID.

I’ll be using this time lapse video of fog, which has the following URL:

www.dailymotion.com/video/x71jlg3

The video’s ID is the unique string of characters at the end of its URL, so my video ID is: x71jlg3.

Adding the Dailymotion SDK

Since we’re using the Dailymotion SDK, we need to declare it as a project dependency. Open your project’s build.gradle file, and add the following:

Code
dependencies {
   implementation fileTree(dir: 'libs', include: ['*.jar'])

//Add the following//

   implementation 'com.dailymotion.dailymotion-sdk-android:sdk:0.1.29'
   implementation 'com.android.support:appcompat-v7:28.0.0'
   implementation 'com.android.support:design:28.0.0'
   implementation 'com.android.support.constraint:constraint-layout:1.1.3'
   testImplementation 'junit:junit:4.12'
   androidTestImplementation 'com.android.support.test:runner:1.0.2'

}

When prompted, select “Sync Project with Gradle Files.”

Note that by default the Dailymotion SDK only gives you access to Dailymotion’s public data, such as a video’s title and description. You can perform some additional tasks by registering your application with the Dailymotion platform, but since we just want to embed a video, we don’t need to worry about registering our application.

If you’re interesting in adding more Dailymotion functionality to your apps, then you can learn more about registering your application with Dailymotion, over at the official docs.

Requesting Internet access

Once again, we’re streaming content from the World Wide Web, so our project requires the Internet permission:

Code
<uses-permission android:name="android.permission.INTERNET" />

Every Activity that displays Dailymotion content must have an “android:configChanges” attribute, so add the following to your MainActivity:

Code
<activity android:name=".MainActivity"
   android:configChanges="orientation|screenSize">

Adding Dailymotion’s PlayerWebView widget

The major component of the Dailymotion SDK is a PlayerWebView UI element, which provides a thin wrapper around Android’s WebView component.

We’ll be exploring WebViews in more detail in the following section, but WebViews essentially give you a way to embed web pages in your application. If we weren’t using the SDK’s specialized PlayerWebView, then we might use Android’s vanilla WebView component to display an entire Dailymotion web page within our application.

Instead, let’s add a PlayerWebView to our layout:

Code
<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"
  tools:context=".MainActivity">

   <com.dailymotion.android.player.sdk.PlayerWebView
      android:id="@+id/dailymotionPlayer"
      android:layout_width="match_parent"
      android:layout_height="215dp">
   </com.dailymotion.android.player.sdk.PlayerWebView>

</android.support.constraint.ConstraintLayout>

Configuring our Dailymotion PlayerWebView

Now we’ve implemented the PlayerWebView widget, we need to configure the player in our corresponding Activity class.

Open your MainActivity, and start by getting a reference to the PlayerWebView:

Code
dailyMotionPlayer= (PlayerWebView) findViewById(R.id.dailymotionPlayer);

Then, call “dailyMotionPlayer.load” and pass it the video ID we retrieved earlier:

Code
dailyMotionPlayer.load("x71jlg3");

This gives us the following:

Code
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.dailymotion.android.player.sdk.PlayerWebView;

import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

   private PlayerWebView dailyMotionPlayer;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);

//Retrieve our PlayerWebView//

       dailyMotionPlayer= (PlayerWebView) findViewById(R.id.dailymotionPlayer);
       Map<String, String> playerParams = new HashMap<>();

//Load the video with our parameters//

       playerParams.put("key", "value");

//Pass the video ID//

       dailyMotionPlayer.load("x71jlg3");
   }
}

Install your project on a physical Android device or emulator, and your Dailymotion video should start playing automatically.

Embedding a Vimeo video

When it comes to embedding video content, you’ll typically want to use a platform-specific API or platform-specific SDK wherever possible. But, what if there isn’t an SDK or API available, for the video-sharing platform you have in mind?

In these scenarios, you can use Android’s WebView component to display the video as a web page that’s embedded in your Activity’s layout. In this final section, I’ll show you how to embed a video from the popular Vimeo platform, using a WebView.

In addition to displaying video content, WebViews can be useful in a number of other scenarios. For example, imagine you have some content that needs to be updated regularly; hosting that content online and then displaying it in your application via a WebView gives you the flexibility to change that content online at any time, without having to publish a new version of your app. However, just be cautious when using WebViews as they don’t support many of the features you’d typically expect from a stand-alone web browser. In particular, WebViews lack an address bar or navigational controls, which can make their content difficult for users to interact with.

Before using a WebView, you should always consider whether an alternative solution might be more appropriate, for example you could offload the content to the device’s default web browser, or implement Chrome Custom Tabs.

Updating the Manifest

Since we’re streaming a video from the Internet, we need to add the Internet permission to our Manifest:

Code
<uses-permission android:name="android.permission.INTERNET" />

I’m also going to launch MainActivity in landscape mode:

Code
<activity android:name=".MainActivity"
   android:screenOrientation="landscape">

Adding a WebView to our UI

Next, let’s add a WebView to our app. We can either add the WebView to our Activity’s layout, or turn the entire Activity into a WebView, by implementing it in our application’s onCreate() method.

I’m going to add a WebView to our application’s layout:

Code
<?xml version="1.0" encoding="utf-8"?>
<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"
   tools:context=".MainActivity">

   <WebView
       android:id="@+id/myWebView"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_marginTop="8dp"
       android:layout_marginBottom="8dp"
       app:layout_constraintBottom_toBottomOf="parent"
       app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

Choose your video

Once again, we need a video to display, but this time we’re not using a video ID:

  • Head over to Vimeo and choose a video that you want to use; I’ve opted for this winter time lapse.
  • Give the “Share” button a click.
  • Select the “Embed” icon; this will provide you with an embed code that should look something like this:
Code
<iframe src="https://player.vimeo.com/video/163996646" width="640" height="291" frameborder="0" allowfullscreen></iframe>

This code provides the following information:

  • iframe. Specifies that we’re embedding another HTML page inside the current context.
  • src. The video’s path, so your app knows where to find this video.
  • width / height. The video’s dimensions.
  • frameborder. Whether to display a border around the video’s frame. The possible values are border (1) and no border (0).
  • allowfullscreen. This enables the video to be displayed in fullscreen mode.

I’m going to add this embed code to my project as a string, so you need to copy/paste this information into the following template:

Code
String vimeoVideo = "<html>&lt;body>YOUR LINK GOES HERE</iframe></body></html>";

Frustratingly, we need to make a few changes before the embed code is compatible with our Android app. First, we need to add a few “\” characters, so that Android Studio doesn’t complain about incorrect formatting:

Code
String vimeoVideo = "<html><body><iframe src=\"https://player.vimeo.com/video/163996646\" width=\"640\" height=\"291\" frameborder=\"0\" allowfullscreen></iframe></body></html>";

Finally, the default video dimensions may be too large for some Android smartphone screens.
In production, you’d typically experiment with various dimensions to see what delivers the best results, across as many different screen configurations as possible. However, to help keep this article from getting out of control, I’m just going to use the following, which should provide good results on your “typical” Android smartphone screen:

Code
String vimeoVideo = "<html><body><iframe src=\"https://player.vimeo.com/video/163996646\" width=\"420\" height=\"315\" frameborder=\"0\" allowfullscreen></iframe></body></html>";

Displaying a web page in your Android app

Now we’ve created our layout and have our HTML all ready to go, open your MainActivity and lets implement our WebView.

Start by adding the HTML string:

Code
String vimeoVideo = "<html><body><iframe width=\"420\" height=\"315\" src=\"https://player.vimeo.com/video/163996646?player_id=player\" frameborder=\"0\" allowfullscreen></iframe></body></html>";

Next, we need to load the above web page in our WebView, using the loadUrl() method:

Code
webView.loadUrl(request.getUrl().toString());

JavaScript is disabled by default, so we’ll need to enable it in our WebView.

Every time you create a WebView, it’s automatically assigned a set of default WebSettings. We’ll retrieve this WebSettings object, using the getSettings() method, and then enable JavaScript, using setJavaScriptEnabled().

Code
WebSettings webSettings = webView.getSettings();
       webSettings.setJavaScriptEnabled(true);

After adding all this to your MainActivity, your code should look something like this:

Code
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);

       String vimeoVideo = "<html><body><iframe width=\"420\" height=\"315\" src=\"https://player.vimeo.com/video/163996646?player_id=player\" frameborder=\"0\" allowfullscreen></iframe></body></html>";

       WebView webView = (WebView) findViewById(R.id.myWebView);
       webView.setWebViewClient(new WebViewClient() {
           @Override
           public boolean shouldOverrideUrlLoading(WebView webView, WebResourceRequest request) {

               webView.loadUrl(request.getUrl().toString());
               return true;
           }
       });
       WebSettings webSettings = webView.getSettings();
       webSettings.setJavaScriptEnabled(true);
       webView.loadData(vimeoVideo, "text/html", "utf-8");
   }
}

Testing your Vimeo app

You know the drill by now: install this project on a physical Android device or AVD. The WebView isn’t set to play automatically, so you’ll need to give the video a tap, to reveal Vimeo’s media controls. You can then play, pause, rewind and fast-forward the video, to make sure it’s functioning correctly.

Wrapping up

In this article, I showed you how to add YouTube, Vimeo and Dailymotion videos to your apps, using platform-specific APIs and SDKs, and Android’s own WebView component. I also showed you how to bundle a video file with your application, so it can be stored and played locally.

What’s your favourite way to display multimedia content to your users? Let us know in the comments below!

You might like