In this tutorial we will be playing a youtube video using youtube iframe api.I Recently faced this problem in one of my live project.(Tested in Android 4+ and 5+ versions)
So here we will be creating a html page placed in assets folder then displaying that page in the webview. Also to play video full screen i've made bit of adjustments in the div tag of html content.
Since android webview isnt fully javascript enabled in lower versions then 5.0 so using 3rd party customized webview here named videoenabledwebview.
Also android web interface is been implemented here. Android clicks interact with javascript methods in order to play and pause youtube videos.
1. YoutubeActivity.java
1. activity_example.xml
5. AndroidManifest.xml
HTML FILE PLACED IN ASSETS FOLDER
1. example.html
References for VideoEnableWebView: https://github.com/cprcrack/VideoEnabledWebView
So here we will be creating a html page placed in assets folder then displaying that page in the webview. Also to play video full screen i've made bit of adjustments in the div tag of html content.
Since android webview isnt fully javascript enabled in lower versions then 5.0 so using 3rd party customized webview here named videoenabledwebview.
Also android web interface is been implemented here. Android clicks interact with javascript methods in order to play and pause youtube videos.
1. YoutubeActivity.java
public class YoutubeActivity extends ActionBarActivity { private VideoEnabledWebView webView; private VideoEnabledWebChromeClient webChromeClient; Button btn, pause; InputStream is; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_example); webView = (VideoEnabledWebView) findViewById(R.id.webView); View nonVideoLayout = findViewById(R.id.nonVideoLayout); ViewGroup videoLayout = (ViewGroup) findViewById(R.id.videoLayout); WebSettings ws = webView.getSettings(); ws.setJavaScriptEnabled(true); ws.setAllowFileAccess(true); if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.ECLAIR) { try { WebSettings.class.getMethod("setLightTouchEnabled", new Class[]{Boolean.TYPE}); Log.d("Enabling HTML5-Features", "Enabling HTML5-Features"); Method m1 = WebSettings.class.getMethod("setDomStorageEnabled", new Class[]{Boolean.TYPE}); m1.invoke(ws, Boolean.TRUE); Method m2 = WebSettings.class.getMethod("setDatabaseEnabled", new Class[]{Boolean.TYPE}); m2.invoke(ws, Boolean.TRUE); Method m3 = WebSettings.class.getMethod("setDatabasePath", new Class[]{String.class}); m3.invoke(ws, "/data/data/" + getPackageName() + "/databases/"); Method m4 = WebSettings.class.getMethod("setAppCacheMaxSize", new Class[]{Long.TYPE}); m4.invoke(ws, 1024*1024*8); Method m5 = WebSettings.class.getMethod("setAppCachePath", new Class[]{String.class}); m5.invoke(ws, "/data/data/" + getPackageName() + "/cache/"); Method m6 = WebSettings.class.getMethod("setAppCacheEnabled", new Class[]{Boolean.TYPE}); m6.invoke(ws, Boolean.TRUE); Log.d("Enabled HTML5-Features", "Enabled HTML5-Features"); } catch (NoSuchMethodException e) { Log.e("Enabled HTML5-Features", "Reflection fail", e); } catch (InvocationTargetException e) { Log.e("Enabled HTML5-Features", "Reflection fail", e); } catch (IllegalAccessException e) { Log.e("Enabled HTML5-Features", "Reflection fail", e); } webView.getSettings().setPluginState(PluginState.ON); webView.getSettings().setJavaScriptEnabled(true); View loadingView = getLayoutInflater().inflate( R.layout.view_loading_video, null); webChromeClient = new VideoEnabledWebChromeClient(nonVideoLayout, videoLayout, loadingView, webView) { @Override public void onProgressChanged(WebView view, int progress) { } }; webChromeClient .setOnToggledFullscreen(new VideoEnabledWebChromeClient.ToggledFullscreenCallback() { @SuppressLint("NewApi") @Override public void toggledFullscreen(boolean fullscreen) { if (fullscreen) { WindowManager.LayoutParams attrs = getWindow() .getAttributes(); attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN; attrs.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON; getWindow().setAttributes(attrs); if (android.os.Build.VERSION.SDK_INT >= 14) { getWindow() .getDecorView() .setSystemUiVisibility( View.SYSTEM_UI_FLAG_LOW_PROFILE); } } else { WindowManager.LayoutParams attrs = getWindow() .getAttributes(); attrs.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN; attrs.flags &= ~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON; getWindow().setAttributes(attrs); if (android.os.Build.VERSION.SDK_INT >= 14) { getWindow().getDecorView() .setSystemUiVisibility( View.SYSTEM_UI_FLAG_VISIBLE); } } } }); webView.addJavascriptInterface(new WebAppInterface(this), "Android"); webView.setWebChromeClient(webChromeClient); webView.setWebViewClient(new WebViewClient() { public void onPageFinished(WebView view, String url) { new Handler().postDelayed(new Runnable() { @Override public void run() { //webView.loadUrl("javascript:playVideo()"); } }, 3000); } }); btn = (Button) findViewById(R.id.btn); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { webView.loadUrl("javascript:playVideo()"); } }); pause = (Button) findViewById(R.id.pause); pause.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { webView.loadUrl("javascript:pauseVideo()"); } }); try { webView.loadUrl("file:///android_asset/example.html"); } catch (IOException e) { e.printStackTrace(); } } } public static String convertStreamToString(InputStream is) throws IOException { Writer writer = new StringWriter(); char[] buffer = new char[2048]; try { Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); int n; while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } } finally { is.close(); } String text = writer.toString(); return text; } @Override public void onBackPressed() { // Notify the VideoEnabledWebChromeClient, and handle it ourselves if it // doesn't handle it if (!webChromeClient.onBackPressed()) { if (webView.canGoBack()) { webView.goBack(); } else { // Standard back button implementation (for example this could // close the app) super.onBackPressed(); } } } }2. VideoEnabledWebChromeClient.java
public class VideoEnabledWebChromeClient extends WebChromeClient implements MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener { public interface ToggledFullscreenCallback { public void toggledFullscreen(boolean fullscreen); } private View activityNonVideoView; private ViewGroup activityVideoView; private View loadingView; private VideoEnabledWebView webView; private boolean isVideoFullscreen; // Indicates if the video is being displayed using a custom view (typically full-screen) private FrameLayout videoViewContainer; private CustomViewCallback videoViewCallback; private ToggledFullscreenCallback toggledFullscreenCallback; /** * Never use this constructor alone. * This constructor allows this class to be defined as an inline inner class in which the user can override methods */ @SuppressWarnings("unused") public VideoEnabledWebChromeClient() { } /** * Builds a video enabled WebChromeClient. * @param activityNonVideoView A View in the activity's layout that contains every other view that should be hidden when the video goes full-screen. * @param activityVideoView A ViewGroup in the activity's layout that will display the video. Typically you would like this to fill the whole layout. */ @SuppressWarnings("unused") public VideoEnabledWebChromeClient(View activityNonVideoView, ViewGroup activityVideoView) { this.activityNonVideoView = activityNonVideoView; this.activityVideoView = activityVideoView; this.loadingView = null; this.webView = null; this.isVideoFullscreen = false; } /** * Builds a video enabled WebChromeClient. * @param activityNonVideoView A View in the activity's layout that contains every other view that should be hidden when the video goes full-screen. * @param activityVideoView A ViewGroup in the activity's layout that will display the video. Typically you would like this to fill the whole layout. * @param loadingView A View to be shown while the video is loading (typically only used in API level <11). Must be already inflated and not attached to a parent view. */ @SuppressWarnings("unused") public VideoEnabledWebChromeClient(View activityNonVideoView, ViewGroup activityVideoView, View loadingView) { this.activityNonVideoView = activityNonVideoView; this.activityVideoView = activityVideoView; this.loadingView = loadingView; this.webView = null; this.isVideoFullscreen = false; } /** * Builds a video enabled WebChromeClient. * @param activityNonVideoView A View in the activity's layout that contains every other view that should be hidden when the video goes full-screen. * @param activityVideoView A ViewGroup in the activity's layout that will display the video. Typically you would like this to fill the whole layout. * @param loadingView A View to be shown while the video is loading (typically only used in API level <11). Must be already inflated and not attached to a parent view. * @param webView The owner VideoEnabledWebView. Passing it will enable the VideoEnabledWebChromeClient to detect the HTML5 video ended event and exit full-screen. * Note: The web page must only contain one video tag in order for the HTML5 video ended event to work. This could be improved if needed (see Javascript code). */ @SuppressWarnings("unused") public VideoEnabledWebChromeClient(View activityNonVideoView, ViewGroup activityVideoView, View loadingView, VideoEnabledWebView webView) { this.activityNonVideoView = activityNonVideoView; this.activityVideoView = activityVideoView; this.loadingView = loadingView; this.webView = webView; this.isVideoFullscreen = false; } /** * Indicates if the video is being displayed using a custom view (typically full-screen) * @return true it the video is being displayed using a custom view (typically full-screen) */ public boolean isVideoFullscreen() { return isVideoFullscreen; } /** * Set a callback that will be fired when the video starts or finishes displaying using a custom view (typically full-screen) * @param callback A VideoEnabledWebChromeClient.ToggledFullscreenCallback callback */ @SuppressWarnings("unused") public void setOnToggledFullscreen(ToggledFullscreenCallback callback) { this.toggledFullscreenCallback = callback; } @Override public void onShowCustomView(View view, CustomViewCallback callback) { if (view instanceof FrameLayout) { // A video wants to be shown FrameLayout frameLayout = (FrameLayout) view; View focusedChild = frameLayout.getFocusedChild(); // Save video related variables this.isVideoFullscreen = true; this.videoViewContainer = frameLayout; this.videoViewCallback = callback; // Hide the non-video view, add the video view, and show it activityNonVideoView.setVisibility(View.INVISIBLE); activityVideoView.addView(videoViewContainer, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); activityVideoView.setVisibility(View.VISIBLE); if (focusedChild instanceof android.widget.VideoView) { // android.widget.VideoView (typically API level <11) android.widget.VideoView videoView = (android.widget.VideoView) focusedChild; // Handle all the required events videoView.setOnPreparedListener(this); videoView.setOnCompletionListener(this); videoView.setOnErrorListener(this); } else { // Other classes, including: // - android.webkit.HTML5VideoFullScreen$VideoSurfaceView, which inherits from android.view.SurfaceView (typically API level 11-18) // - android.webkit.HTML5VideoFullScreen$VideoTextureView, which inherits from android.view.TextureView (typically API level 11-18) // - com.android.org.chromium.content.browser.ContentVideoView$VideoSurfaceView, which inherits from android.view.SurfaceView (typically API level 19+) // Handle HTML5 video ended event only if the class is a SurfaceView // Test case: TextureView of Sony Xperia T API level 16 doesn't work fullscreen when loading the javascript below if (webView != null && webView.getSettings().getJavaScriptEnabled() && focusedChild instanceof SurfaceView) { // Run javascript code that detects the video end and notifies the Javascript interface String js = "javascript:"; js += "var _ytrp_html5_video_last;"; js += "var _ytrp_html5_video = document.getElementsByTagName('video')[0];"; js += "if (_ytrp_html5_video != undefined && _ytrp_html5_video != _ytrp_html5_video_last) {"; { js += "_ytrp_html5_video_last = _ytrp_html5_video;"; js += "function _ytrp_html5_video_ended() {"; { js += "_VideoEnabledWebView.notifyVideoEnd();"; // Must match Javascript interface name and method of VideoEnableWebView } js += "}"; js += "_ytrp_html5_video.addEventListener('ended', _ytrp_html5_video_ended);"; } js += "}"; webView.loadUrl(js); } } // Notify full-screen change if (toggledFullscreenCallback != null) { toggledFullscreenCallback.toggledFullscreen(true); } } } @Override @SuppressWarnings("deprecation") public void onShowCustomView(View view, int requestedOrientation, CustomViewCallback callback) // Available in API level 14+, deprecated in API level 18+ { onShowCustomView(view, callback); } @Override public void onHideCustomView() { // This method should be manually called on video end in all cases because it's not always called automatically. // This method must be manually called on back key press (from this class' onBackPressed() method). if (isVideoFullscreen) { // Hide the video view, remove it, and show the non-video view activityVideoView.setVisibility(View.INVISIBLE); activityVideoView.removeView(videoViewContainer); activityNonVideoView.setVisibility(View.VISIBLE); // Call back (only in API level <19, because in API level 19+ with chromium webview it crashes) if (videoViewCallback != null && !videoViewCallback.getClass().getName().contains(".chromium.")) { videoViewCallback.onCustomViewHidden(); } // Reset video related variables isVideoFullscreen = false; videoViewContainer = null; videoViewCallback = null; // Notify full-screen change if (toggledFullscreenCallback != null) { toggledFullscreenCallback.toggledFullscreen(false); } } } @Override public View getVideoLoadingProgressView() // Video will start loading { if (loadingView != null) { loadingView.setVisibility(View.VISIBLE); return loadingView; } else { return super.getVideoLoadingProgressView(); } } @Override public void onPrepared(MediaPlayer mp) // Video will start playing, only called in the case of android.widget.VideoView (typically API level <11) { if (loadingView != null) { loadingView.setVisibility(View.GONE); } } @Override public void onCompletion(MediaPlayer mp) // Video finished playing, only called in the case of android.widget.VideoView (typically API level <11) { onHideCustomView(); } @Override public boolean onError(MediaPlayer mp, int what, int extra) // Error while playing video, only called in the case of android.widget.VideoView (typically API level <11) { return false; // By returning false, onCompletion() will be called } /** * Notifies the class that the back key has been pressed by the user. * This must be called from the Activity's onBackPressed(), and if it returns false, the activity itself should handle it. Otherwise don't do anything. * @return Returns true if the event was handled, and false if was not (video view is not visible) */ @SuppressWarnings("unused") public boolean onBackPressed() { if (isVideoFullscreen) { onHideCustomView(); return true; } else { return false; } } }3. VideoEnabledWebView.java
public class VideoEnabledWebView extends WebView { public class JavascriptInterface { @android.webkit.JavascriptInterface @SuppressWarnings("unused") public void notifyVideoEnd() // Must match Javascript interface method of VideoEnabledWebChromeClient { Log.d("___", "GOT IT"); // This code is not executed in the UI thread, so we must force that to happen new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { if (videoEnabledWebChromeClient != null) { videoEnabledWebChromeClient.onHideCustomView(); } } }); } } private VideoEnabledWebChromeClient videoEnabledWebChromeClient; private boolean addedJavascriptInterface; @SuppressWarnings("unused") public VideoEnabledWebView(Context context) { super(context); addedJavascriptInterface = false; } @SuppressWarnings("unused") public VideoEnabledWebView(Context context, AttributeSet attrs) { super(context, attrs); addedJavascriptInterface = false; } @SuppressWarnings("unused") public VideoEnabledWebView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); addedJavascriptInterface = false; } /** * Indicates if the video is being displayed using a custom view (typically full-screen) * @return true it the video is being displayed using a custom view (typically full-screen) */ @SuppressWarnings("unused") public boolean isVideoFullscreen() { return videoEnabledWebChromeClient != null && videoEnabledWebChromeClient.isVideoFullscreen(); } /** * Pass only a VideoEnabledWebChromeClient instance. */ @Override @SuppressLint("SetJavaScriptEnabled") public void setWebChromeClient(WebChromeClient client) { getSettings().setJavaScriptEnabled(true); if (client instanceof VideoEnabledWebChromeClient) { this.videoEnabledWebChromeClient = (VideoEnabledWebChromeClient) client; } super.setWebChromeClient(client); } @Override public void loadData(String data, String mimeType, String encoding) { addJavascriptInterface(); super.loadData(data, mimeType, encoding); } @Override public void loadDataWithBaseURL(String baseUrl, String data, String mimeType, String encoding, String historyUrl) { addJavascriptInterface(); super.loadDataWithBaseURL(baseUrl, data, mimeType, encoding, historyUrl); } @Override public void loadUrl(String url) { addJavascriptInterface(); super.loadUrl(url); } @Override public void loadUrl(String url, Map<String, String> additionalHttpHeaders) { addJavascriptInterface(); super.loadUrl(url, additionalHttpHeaders); } private void addJavascriptInterface() { if (!addedJavascriptInterface) { // Add javascript interface to be called when the video ends (must be done before page load) //noinspection all addJavascriptInterface(new JavascriptInterface(), "_VideoEnabledWebView"); // Must match Javascript interface name of VideoEnabledWebChromeClient addedJavascriptInterface = true; } } }XML Layouts Goes Here :
1. activity_example.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".YoutubeActivity" > <Button android:id="@+id/btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:text="Play" /> <Button android:id="@+id/pause" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@+id/btn" android:text="Pause" /> <!-- View that will be hidden when video goes fullscreen --> <RelativeLayout android:id="@+id/nonVideoLayout" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@+id/btn" > <com.example.androidyoutube.VideoEnabledWebView android:id="@+id/webView" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout> <!-- View where the video will be shown when video goes fullscreen --> <RelativeLayout android:id="@+id/videoLayout" android:layout_width="match_parent" android:layout_height="match_parent" > <View android:id="@+id/videoLoading" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:visibility="invisible" /> --> </RelativeLayout> </RelativeLayout>2. custom_screen.xml
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"> <FrameLayout android:id="@+id/fullscreen_custom_content" android:visibility="gone" android:background="@color/black" android:layout_width="match_parent" android:layout_height="match_parent" /> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:id="@+id/error_console" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content" /> <FrameLayout android:id="@+id/main_content" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout> </FrameLayout>3. video_loading_progress.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/progress_indicator" android:orientation="vertical" android:layout_centerInParent="true" android:layout_width="wrap_content" android:layout_height="wrap_content"> <ProgressBar android:id="@android:id/progress" style="?android:attr/progressBarStyleLarge" android:layout_gravity="center" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:paddingTop="5dip" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="loading_video" android:textSize="14sp" android:textColor="?android:attr/textColorPrimary" /> </LinearLayout>4.view_loading_video.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#000000" > <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" android:layout_centerInParent="true" > <ProgressBar android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:indeterminate="true" style="?android:attr/progressBarStyleLarge" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="8dp" android:layout_marginBottom="24dp" android:textAppearance="?android:attr/textAppearanceMedium" android:textColor="#a3a3a3" android:text="loading" /> </LinearLayout> </RelativeLayout>
5. AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.androidyoutube" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="11" android:targetSdkVersion="21" /> <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:hardwareAccelerated="true" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".YoutubeActivity" android:screenOrientation="landscape" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
HTML FILE PLACED IN ASSETS FOLDER
1. example.html
<!DOCTYPE html> <html> <head> <head> <meta charset="utf-8" /> <title> Fullscreen Div </title> <style> .overlay { position: fixed; width: 100%; height: 100%; left: 0; top: 0; background: rgba(51,51,51,0.7); z-index: 10; } </style> </head> <body> <!-- 1. The <iframe> (and video player) will replace this <div> tag. --> <div id="player" class='overlay'></div> <script async="true"> var mUrl=""; var tag = document.createElement('script'); tag.src = "https://www.youtube.com/iframe_api"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); // 3. This function creates an <iframe> (and YouTube player) // after the API code downloads. var player; function showAndroidToast(toast) { mUrl=toast; //onYouTubeIframeAPIReady(); } function showAndroidToastTwo(toast) { Android.showToast(toast); mUrl=toast; //$("#ytplayer").pauseVideo(); //document.getElementById('ytplayer').src="http://www.youtube.com/embed/Bm_vnhCpH_M"; //player.pauseVideo(); // document.getElementById('ytplayer').pauseVideo(); //stopVideo(); player.playVideo(); // document.getElementById("ytplayer").innerHTML = 'pauseVideo()'; } function playVideo() { player.playVideo(); } function pauseVideo() { player.pauseVideo(); } function getcurrentduration() { player.getcurrentduration(); } // 2. This code loads the IFrame Player API code asynchronously. //'Bm_vnhCpH_M', , 'controls': 0 function onYouTubeIframeAPIReady() { player = new YT.Player('player', { videoId:'SEZbZK4jFLY', playerVars: { 'autoplay': 1}, events: { 'onReady': onPlayerReady, 'onStateChange': onPlayerStateChange } }); } // 4. The API will call this function when the video player is ready. function onPlayerReady(event) { //event.target.playVideo(); } // 5. The API calls this function when the player's state changes. // The function indicates that when playing a video (state=1), // the player should play for six seconds and then stop. var done = false; function onPlayerStateChange(event) { if (event.data == YT.PlayerState.PLAYING && !done) { //setTimeout(stopVideo, 6000); done = true; } } function stopVideo() { player.stopVideo(); } </script> </body> </html>Output :
References for VideoEnableWebView: https://github.com/cprcrack/VideoEnabledWebView
No comments:
Post a Comment