How to play YouTube videos in WebView on Amazon Fire TV?

3.2k views Asked by At

I want to play a YouTube video in a WebView for Amazon Fire TV.

As of today, there is no official API for playing YouTube videos on Fire OS (link), so I tried to get it working with Android's WebView. In the Android WebView documentation it is written, that the app needs to have hardware acceleration turned on and that the WebView needs to have a WebChromeClient in order to playback YouTube videos.

I tried to get it work but when I start a YouTube video, than I only see the loading spinner in fullscreen mode.

Here is my code:

@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  WebView webview = new WebView(this);
  setContentView(webview);

  webview.getSettings().setBuiltInZoomControls(true);
  webview.getSettings().setJavaScriptEnabled(true);
  webview.setWebChromeClient(new WebChromeClient() {

    @Override
    public void onShowCustomView(View view, CustomViewCallback callback) {
      Log.i("fire-tv", "Show custom view");

      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);
          setContentView(video);
          video.start();
        }
      }
    }

    @Override
    public void onHideCustomView() {
      Log.i("fire-tv", "Hide custom view.");
    }

  });

  webview.setWebViewClient(new WebViewClient() {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
      return false;
    }

  });

  final String mimeType = "text/html";
  final String encoding = "UTF-8";
  String html = getHTML();

  Log.i("fire-tv", "Loading: " + html);
  webview.loadDataWithBaseURL("", html, mimeType, encoding, "");
}

private String getHTML() {
  String html = "<iframe class=\"youtube-player\" style=\"border: 0; width: 100%; height: 100%; padding:0px; margin:0px\" id=\"ytplayer\" type=\"text/html\" src=\"http://www.youtube.com/embed/"
          + "h11u3vtcpaY"
          + "?fs=0\" frameborder=\"0\">\n"
          + "</iframe>\n";

  return html;
}
2

There are 2 answers

2
Ohiovr On

I've written a class to play a youtube video on Fire TV and it also works on the kindle fire as well. As you know, Youtube doesn't have an offical api and we have to resort to using webviews for this. The class I've pasted here has a lot of stuff besides webviews that you might be curious about so I will explain. First of all, you will find that a YouTube playing webview will keep playing when you leave your Activity unless you tell it to stop. So the solution people tell others is to use the onPause and pauseTimers methods to shut up the video. But there is a nasty problem that Amazon has foisted on us and that is the audio and video resources are not released to the rest of the operating system (not a problem with Google Android Lolipop ie Nexus Player). When the resources are held by your app, prime video will not play and amazon will not allow your app on the store. They know darned well we have to use webviews for youtube, so they gave us this little bit of advice:

Q: Can I use an Android WebView and the HTML tag for video playback?
A: Yes, with limitations. Hardware media resources are not currently released by the system when your app pauses or stops. To work around this issue implement your onStop() method to explicitly kill the process for your app:

Amazon source

Like AVGN would say "WHAT WERE THEY THINKING??"

You wouldn't believe how just force killing an app or Activity would lead to tons of problems.. well I'm sure you do, cause you got a few thousand points more than myself.

The only solution I could find is to load a very short 720p HD clip (must have audio!) in the onPause method. I combined it with webView.onPause and .pauseTimers to be sure...

If you use this class please copy my blank.mp4 file to your own server because it might not be there in a month.

Oh but there is more. So you get your YouTube file in your webView... Piece of cake right? Wrong, it doesn't play because in webViews, Html5 usually never auto plays. You cannot set the url to auto play it makes no difference. So my solution was to force a click using java trickery. The way it works is that the webview doesn't load immediately, it takes a variable amount of time for it to fully load. After it does, the video shows a play button icon at the center of the screen. The little remote can't touch it for some reason. But I put in code to force a click in the center of the webview.

Oh and there is one more thing, you must handle audio focus or amazon will not allow your app in the store. Pandora could play in the background unless you handle that.

why Amazon why

package com.ohiovr.modules.youtube;


import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.Point;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.util.Timer;
import java.util.TimerTask;



public class youtubeKindleWebView extends Activity {


    String StringYoutubeUrl;
    WebView webView;

    AFChangeListener hocusFocus;
    private String videoBlanker = "http://ohiovr.com/church_files/blank.mp4";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_generic_web_view);

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        webView = (WebView) findViewById(R.id.webView);
        WebSettings webSettings = webView.getSettings();
        webSettings.setBuiltInZoomControls(true);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setAppCacheEnabled(false);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setUseWideViewPort(true);
        //I used this line in an old and now not used live stream implimentation. It works so I didn't remove it. But you may 
        //want to see if it is nessisary:
        webSettings.setUserAgentString("Mozilla/5.0(iPhone;U;CPUiPhoneOS4_0likeMacOSX;en-us)AppleWebKit/532.9(KHTML,likeGecko)Version/4.0.5Mobile/8A293Safari/6531.22.7");


        webView.setWebViewClient(new Callback()); 
        webView.setWebChromeClient(new WebChromeClient());


    }

    class AFChangeListener implements AudioManager.OnAudioFocusChangeListener {
        @Override
        public void onAudioFocusChange(int focusChange) {
            if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {
                // mp.pause();
            } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
                //  mp.start();
            } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
                //  mp.stop();
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        boolean handled = false;

        switch (keyCode) {
            case KeyEvent.KEYCODE_DPAD_CENTER:
                forceAClick();
                break;
            case KeyEvent.KEYCODE_BUTTON_A:
                // ... handle selections
                handled = true;
                break;
            case KeyEvent.KEYCODE_DPAD_LEFT:
                // ... handle left action
                handled = true;
                break;
            case KeyEvent.KEYCODE_DPAD_RIGHT:
                // ... handle right action
                handled = true;
                break;
        }
        return handled || super.onKeyDown(keyCode, event);
    }


    public void forceAClick() {

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Display display = getWindowManager().getDefaultDisplay();
                        Point size = new Point();
                        display.getSize(size);
                        int width = size.x;
                        int height = size.y;


                        // Obtain MotionEvent object
                        long downTime = SystemClock.uptimeMillis();
                        long eventTime = SystemClock.uptimeMillis() + 100;
                        float x = width / 2;
                        float y = height / 2;
                        // List of meta states found here: developer.android.com/reference/android/view/KeyEvent.html#getMetaState()
                        int metaState = 0;
                        MotionEvent motionEvent = MotionEvent.obtain(
                                downTime,
                                eventTime,
                                MotionEvent.ACTION_DOWN,
                                x,
                                y,
                                metaState
                        );

                        webView.setOnTouchListener(new View.OnTouchListener() {
                            @Override
                            public boolean onTouch(View v, MotionEvent event) {
                                Log.d("on touch", "touched down");
                                return false;
                            }
                        });

                        webView.dispatchTouchEvent(motionEvent);
                    }
                });
            }
        }, 1);

        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Display display = getWindowManager().getDefaultDisplay();
                        Point size = new Point();
                        display.getSize(size);
                        int width = size.x;
                        int height = size.y;


                        // Obtain MotionEvent object
                        long downTime = SystemClock.uptimeMillis();
                        long eventTime = SystemClock.uptimeMillis() + 100;
                        float x = width / 2;
                        float y = height / 2;
                        // List of meta states found here: developer.android.com/reference/android/view/KeyEvent.html#getMetaState()
                        int metaState = 0;
                        MotionEvent motionEvent = MotionEvent.obtain(
                                downTime,
                                eventTime,
                                MotionEvent.ACTION_UP,
                                x,
                                y,
                                metaState
                        );

                        webView.setOnTouchListener(new View.OnTouchListener() {
                            @Override
                            public boolean onTouch(View v, MotionEvent event) {
                                Log.d("on touch", "touched up");
                                return false;
                            }
                        });

                        webView.dispatchTouchEvent(motionEvent);


                    }
                });
            }
        }, 120);


        AudioManager am = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
// Request audio focus for playback
        hocusFocus = new AFChangeListener();
        int result = am.requestAudioFocus(hocusFocus, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
    }


    @Override
    public void onResume() {
        super.onResume();
        webView.onResume();
        webView.resumeTimers();
        StringYoutubeUrl = "https://www.youtube.com/embed/" + getIntent().getStringExtra("youtubeID");
        webView.loadUrl(StringYoutubeUrl);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    }


    private class Callback extends WebViewClient {  //this is important for some reason. don't remove!
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return (false);
        }
    }


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

        webView.loadUrl(videoBlanker);
        webView.pauseTimers();
        webView.onPause();
    }



    /*
    Q: Can I use an Android WebView and the <video> HTML tag for video playback?
    A:
    Yes, with limitations. Hardware media resources are not currently released by the system when your app pauses or stops. To work around this issue implement your onStop() method to explicitly kill the process for your app:

    https://developer.amazon.com/public/solutions/devices/fire-tv/docs/amazon-fire-tv-sdk-frequently-asked-questions
    public void onStop() {
        super.onStop();
        android.os.Process.killProcess(android.os.Process.myPid());
    }
    This issue may also cause instability in the user experience and navigation for your app. The VisualOn SDK is the recommended method for media playback on the device.
    */

    @Override
    protected void onStop() {
        super.onStop();
        // the fascinating part of the next line is that it doesn't kill the application, only this intent
        /////////////  android.os.Process.killProcess(android.os.Process.myPid());
        //no no no! Amazon's advice is bad. It causes a ton of problems.
        //the original problem was that the webview video view frankenhybrid wouldn't release the
        //hardware when the user left the video player.
        //the only and correct solution is to load a very short quiet clip into the webview
        //when the user leaves
        //see onPause for my implementation

    }


}
1
Ohiovr On

Funny thing is, my first answer does answer the question of how to do it with a webview but I found someone else's solution that has a lot of potential using a videoView. Ironically I found it from one of the OPs link:

https://github.com/kslazarev/android-youtube-player

Unlike my solution this plays automatically. Prime video is not affected. There maybe a few other rough edges but this works very well.