Embed Youtube video inside an Android app

145,446

Solution 1

there is an official YouTube Android Player API wich you can use. This is a bit more complicated but it is working better than other solutions using webclients.

First you must register your app in Googles API Console. This is completely free until your app gets over 25k request a month (or something like that). There are complete anf great tutorials under the link. I hope you can understand them. If not, ask! :)

Solution 2

How it looks:

enter image description here

Best solution to my case. I need video fit web view size. Use embed youtube link with your video id. Example:

WebView youtubeWebView; //todo find or bind web view
String myVideoYoutubeId = "-bvXmLR3Ozc";

outubeWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return false;
            }
        });

WebSettings webSettings = youtubeWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setUseWideViewPort(true);

youtubeWebView.loadUrl("https://www.youtube.com/embed/" + myVideoYoutubeId);

Web view xml code

<WebView
        android:id="@+id/youtube_web_view"
        android:layout_width="match_parent"
        android:layout_height="200dp"/>

Solution 3

although I suggest to use youtube api or call new intent and make the system handle it (i.e. youtube app), here some code that can help you, it has a call to an hidden method because you can't pause and resume webview

import java.lang.reflect.Method;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;

import android.app.Activity;

@SuppressLint("SetJavaScriptEnabled")
public class MultimediaPlayer extends Activity
{
    private WebView mWebView;
    private boolean mIsPaused = false;

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

        String media_url = VIDEO_URL;

        mWebView = (WebView) findViewById(R.id.webview);
        mWebView.setWebChromeClient(new WebChromeClient());

        WebSettings ws = mWebView.getSettings();
        ws.setBuiltInZoomControls(true);
        ws.setJavaScriptEnabled(true);

        mIsPaused = true;
        resumeBrowser();
        mWebView.loadUrl(media_url);
    }

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

    @Override
    protected void onResume()
    {
        resumeBrowser();
        super.onResume();
    }

    private void pauseBrowser()
    {
        if (!mIsPaused)
        {
            // pause flash and javascript etc
            callHiddenWebViewMethod(mWebView, "onPause");
            mWebView.pauseTimers();
            mIsPaused = true;
        }
    }

    private void resumeBrowser()
    {
        if (mIsPaused)
        {
            // resume flash and javascript etc
            callHiddenWebViewMethod(mWebView, "onResume");
            mWebView.resumeTimers();
            mIsPaused = false;
        }
    }

    private void callHiddenWebViewMethod(final WebView wv, final String name)
    {
        try
        {
            final Method method = WebView.class.getMethod(name);
            method.invoke(mWebView);
        } catch (final Exception e)
        {}
    }
}

Solution 4

It works like this:

String item = "http://www.youtube.com/embed/";

String ss = "your url";
ss = ss.substring(ss.indexOf("v=") + 2);
item += ss;
DisplayMetrics metrics = getResources().getDisplayMetrics();
int w1 = (int) (metrics.widthPixels / metrics.density), h1 = w1 * 3 / 5;
wv.getSettings().setJavaScriptEnabled(true);
wv.setWebChromeClient(chromeClient);
wv.getSettings().setPluginsEnabled(true);

try {
    wv.loadData(
    "<html><body><iframe class=\"youtube-player\" type=\"text/html5\" width=\""
    + (w1 - 20)
    + "\" height=\""
    + h1
    + "\" src=\""
    + item
    + "\" frameborder=\"0\"\"allowfullscreen\"></iframe></body></html>",
                            "text/html5", "utf-8");
} catch (Exception e) {
    e.printStackTrace();
}

private WebChromeClient chromeClient = new WebChromeClient() {

    @Override
    public void onShowCustomView(View view, CustomViewCallback callback) {
        super.onShowCustomView(view, callback);
        if (view instanceof FrameLayout) {
            FrameLayout frame = (FrameLayout) view;
            if (frame.getFocusedChild() instanceof VideoView) {
                VideoView video = (VideoView) frame.getFocusedChild();
                frame.removeView(video);
                video.start();
            }
        }

    }
};

Solution 5

Embedding the YouTube player in Android is very simple & it hardly takes you 10 minutes,

1) Enable YouTube API from Google API console
2) Download YouTube player Jar file
3) Start using it in Your app

Here are the detailed steps http://www.feelzdroid.com/2017/01/embed-youtube-video-player-android-app-example.html.

Just refer it & if you face any problem, let me know, ill help you

Share:
145,446
Idan
Author by

Idan

No-one really read this one.

Updated on March 03, 2020

Comments

  • Idan
    Idan about 4 years

    I'm using a WebView for displaying embedded Youtube video and that works on Galaxcy S2 (OS 2.3.5) and doesn't on Nexus S (OS 2.3.4), all I get is white screen without any video display.

    Here is the code snippet I'm using and the declarations in Manifest file:

    private WebView wv;
    
    private void setWebView()
    {
    wv = (WebView) findViewById(R.id.webView);
    
    wv.setWebChromeClient(new WebChromeClient());
    
    wv.getSettings().setPluginState(WebSettings.PluginState.ON);
    
    wv.setWebViewClient(new WebViewClient()); 
    
    wv.getSettings();
    
    wv.setBackgroundColor(0x00000000);
    
    wv.setKeepScreenOn(true);
    
    wv.setHorizontalScrollBarEnabled(false);
    wv.setVerticalScrollBarEnabled(false);
    
    wv.getSettings().setBuiltInZoomControls(true);
    
    final String mimeType = "text/html";
    final String encoding = "UTF-8";
    String html = getHTML();
    
    wv.loadDataWithBaseURL("", html, mimeType, encoding, "");
    
    }
    
    
    public String getHTML()
    {
    
    String html = "<html>"
    
        + "<head>"
     + "</head>"
     + "<body style=\"border: 0; padding: 0\">"
     + "<iframe "
     + "type=\"text/html\" "
     + "class=\"youtube-player\" "
     + "width= 100%\""
     + "\" "
     + "height= 95%\""
     + "\" "
     + "src=\"http://www.youtube.com/v/"
     + selected_video 
        + "?controls=0&showinfo=0&showsearch=0&modestbranding=0" +
     "&autoplay=1&fs=1&vq=hd720\" " + "frameborder=\"0\"></iframe>" 
        + "</body>"
        + "</html>";
    
     return html;
    }
    

    Note: the parameter "selected_video" is the hash of the video (VideoID).

    The declarations in Manifest file:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android=http://schemas.android.com/apk/res/android
    .
    .
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"  />
    
    <application
       .
       .
        android:hardwareAccelerated="true"  >
    
        .
        .
    

    Please let me know in case you recognizing anything I should change in my code, or help with a complete code which can support all Android devices and OS for displaying embedded (In-App) Youtube video with high quality.

    UPDATE: Pay attention, the solution I'm looking for should display high resolution video. I got it work on the different devices and OS using VideoView class but the video quality isn't good enough. So any solution including VideoView or WebView or any other way will be accepted only if it makes high quality YouTube video to be displayed. Thanks to all the responders!

  • Idan
    Idan almost 11 years
    To my understanding to use that I must have Youtube app on the device, That's not what I want.
  • Idan
    Idan almost 11 years
    This code doesn't compile (metrics should be Metrics). What should be on "your url" exactly? can you provide a better example?
  • Dylan Vander Berg
    Dylan Vander Berg almost 11 years
    Can't you use developers.google.com/youtube/android/player/reference/com/… YouTubePlayerView to insert the video directly into your app. It needs to be a specific activity, but the method used to initiate the YouTubePlayerView doesn't include an intent and therefore can't launch the youtube application.
  • Gunnar Forsgren - Mobimation
    Gunnar Forsgren - Mobimation over 10 years
    I think the API simply uses code part of library files that come with the YouTube application. So any user of your app will need to have the YouTube app on their phone. Your app could query to see if it is installed and otherwise guide the user to install it.
  • Luis Pena
    Luis Pena about 10 years
    Thanks! How silly of me i couldn't find there's an API for youtube. Lol
  • vuhung3990
    vuhung3990 over 9 years
    Youtube android player api require youtube app installed and google play service, but Embed Youtube video for run on every device
  • Ajith M A
    Ajith M A about 4 years
    The Youtube player api has a limitation that it needs to have Play services and Youtube app installed on the device. If that's not a problem with your target audience, yes this solution can be applied.
  • Ajith M A
    Ajith M A about 4 years
    What does this line exactly do? frame.removeView(video);
  • Samudra Ganguly
    Samudra Ganguly about 3 years
    stackoverflow.com/q/67406221/13146544 please help me if possible.. The time bar in Minimal player style is not working.