Zain I.
Zain I.

Reputation: 205

Android WebView - Youtube videos not playing within the application

I have an activity which is displaying a web page using a WebView. Within that page, there is a link to a YouTube video (so it's not a video I can or need to embed).

The problem is that the video won't play - When i click on the play button, a error page appears saying " Webpage not available The webpage at vnd.youtube:SVf8Ghl6d8xx might be temporarily down and blah blah blah !!!"

Please only answer if you know what i want! I have gone through almost all related posts on stackoverflow so there is no need of references to other posts/question.

MainActivity.java

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


        // add the custom view to the action bar
        webView = (WebView) findViewById(R.id.webView1);
        webView.getSettings().setJavaScriptEnabled(true);

        if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2)
            webView.getSettings().setPluginState(WebSettings.PluginState.ON);   //Helps flash run on a device

        webView.getSettings().setBuiltInZoomControls(true);

        webView.setWebViewClient(new WebViewClient ());
        webView.setWebChromeClient(new WebChromeClient());
        webView.getSettings().setUseWideViewPort(true);
        //webView.getSettings().setUseWideViewPort(false);
        webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        webView.loadUrl(url);

    }

The following code make it run in the youtube app but i want the videos to run in my app :(

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


        // add the custom view to the action bar
        webView = (WebView) findViewById(R.id.webView1);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setBuiltInZoomControls(true);

        if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2)
                    webView.getSettings().setPluginState(WebSettings.PluginState.ON);


        webView.setWebViewClient(new WebViewClient () {
            @ Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.startsWith("vnd.youtube")){

                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));

                return true;
            }
            else return false;

            }
        });

        webView.setWebChromeClient(new WebChromeClient());
        webView.getSettings().setUseWideViewPort(true);
        //webView.getSettings().setUseWideViewPort(false);
        webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        webView.loadUrl(url);

    }

Upvotes: 3

Views: 5459

Answers (3)

Sunil Sunny
Sunil Sunny

Reputation: 3994

  1. Go to Google Developer Console and select or create a new project.

  2. On the left sidebar, select APIs under APIs & auth and turn the status ON for YouTube Data API v3.

  3. On the left sidebar, select Credentials and Create new key under Public API access.

  4. When popup comes asking you to choose platform, select Android Key.

  5. Paste the SHA-1 key and your project’s package name separated by semicolon(;).

  6. Click on create. Now you should see the API KEY on the dashboard.

download YouTubeAPI jar from here

https://developers.google.com/youtube/android/player/downloads/

Create a layout like this

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<com.google.android.youtube.player.YouTubePlayerView
    android:id="@+id/youtube_player"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/black"
    android:layout_centerInParent="true" />

  </RelativeLayout>

Your activity should look something like this

public class CustomYouTubePlayer extends YouTubeBaseActivity implements   YouTubePlayer.OnInitializedListener{


private String API_KEY="your key";
private String VIDEO_ID;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    /** attaching layout xml **/
    setContentView(R.layout.youtube_player);

    /** Initializing YouTube player view **/
    VIDEO_ID = getIntent().getExtras().getString(FinalVariables.YOUTUBE_ID);
    YouTubePlayerView youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtube_player);
    youTubePlayerView.initialize(API_KEY, this);
}

@Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored) {

    player.setShowFullscreenButton(false);
    /** add listeners to YouTubePlayer instance **/
    player.setPlayerStateChangeListener(playerStateChangeListener);
    player.setPlaybackEventListener(playbackEventListener);

    /** Start buffering **/
    if (!wasRestored) {
        player.loadVideo(VIDEO_ID);
    }
}
private YouTubePlayer.PlaybackEventListener playbackEventListener = new YouTubePlayer.PlaybackEventListener() {

    @Override
    public void onBuffering(boolean arg0) {
    }

    @Override
    public void onPaused() {
    }

    @Override
    public void onPlaying() {
    }

    @Override
    public void onSeekTo(int arg0) {
    }

    @Override
    public void onStopped() {
    }

};

 private YouTubePlayer.PlayerStateChangeListener playerStateChangeListener = new YouTubePlayer.PlayerStateChangeListener() {

    @Override
    public void onAdStarted() {
    }

    @Override
    public void onError(YouTubePlayer.ErrorReason arg0) {
    }

    @Override
    public void onLoaded(String arg0) {
    }

    @Override
    public void onLoading() {
    }

    @Override
    public void onVideoEnded() {
        finish();
    }

    @Override
    public void onVideoStarted() {
    }
};
} 

Just pass the video id and that's all simple as that..

Edit

if this is your YouTube link https://www.youtube.com/watch?v=rql_F8H3h9E then your video_id=rql_F8H3h9E Extract your video id from YouTube link and sent to this activity as extra variable.

Upvotes: 4

King of Masses
King of Masses

Reputation: 18775

For this you will convert the iFrame code of your embed YouTube video to a string and load it to webview as a string in your application.

For example,

 String frameVideo = "<html><body>Youtube video .. <br> <iframe width="320" height="315" src="https://www.youtube.com/embed/lY2H2ZP56K4" frameborder="0" allowfullscreen></iframe></body></html>";

then load it to your webview after all the normal webview settings

WebView displayVideo = (WebView)findViewById(R.id.webView);
displayVideo.setWebViewClient(new WebViewClient(){
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    return false;
                }
            });
  WebSettings webSettings = displayVideo.getSettings();
            webSettings.setJavaScriptEnabled(true);
            displayVideo.loadData(frameVideo, "text/html", "utf-8");

For more information refer this links 1 2 3

Upvotes: 0

Arko Chatterjee
Arko Chatterjee

Reputation: 21

The Best Way you could embed youtube videos in the app is by using Youtube API

The YouTube Android Player API enables you to incorporate video playback functionality into your Android applications. The API defines methods for loading and playing YouTube videos (and playlists) and for customizing and controlling the video playback experience.

Upvotes: 2

Related Questions