您现在的位置是:首页 > 技术教程 正文

Android WebView访问网页+自动播放视频+自动全屏+切换横屏

admin 阅读: 2024-03-27
后台-插件-广告管理-内容页头部广告(手机)

一、引言

        近期,我发现电视家、火星直播等在线看电视直播的软件都已倒闭,而我奶奶也再无法通过这些平台看电视了。她已六十多岁,快七十岁啦。这些平台的倒下对我来说其实没有多大的影响,但是对于文化不多的她而言,生活中却是少了一大乐趣。因为自己学过编程,所以我想帮她解决这个问题。她只听得懂白话,又最爱看“广东珠江台”,因此,我通过Android的编程技术,为她专门定制一款可以自动看广东珠江台的App,打开即用,免了点来点去的麻烦。虽说需求很小、只够她一人使用,但实现起来却并不简单呀。通过两天时间的深入钻研,最终我还是把这个小需求给实现了。为此编写一篇博客,如果日后自己还需要解决这样的问题时,我就直接ctrl+c加ctrl+v。当然,也希望这篇博客能够为你提供一些指导和帮助。

二、访问网页视频+自动播放的实现思路

        由于许多的m3u8链接都已经失效,现在看电视直播只能通过一些官方网页来实现,比如央视网等等。那么,访问网页的话是可以通过Android的WebView来实现,实现的方法非常简单,就是在Activity界面之中添加一个WebView空间,然后通过下面的代码来访问网页:

  1. main_wv = findViewById(R.id.main_wv);
  2. main_wv.setWebViewClient(new WebViewClient());
  3. main_wv.setWebChromeClient(new WebChromeClient());
  4. main_wv.loadUrl("https://***.***");

        但是这样的话,最多也只能够竖屏中观看视频,显示十分地有限,而且还不会自动播放,如图:

        所以,这里先介绍实现网页访问+自动播放的思路。WebView可以通过自定义的设置来控制它是否支持JavaScript脚本注入,即通过js来实现网页视频的自动播放。第一步是对WebView进行设置,而第二步是执行js自动播放视频的脚本,代码如下:

        设置WebView支持js脚本

  1. WebSettings settings = main_wv.getSettings(); // main_wv为WebView控件
  2. settings.setJavaScriptEnabled(true);

        执行js自动播放视频的脚本

  1. String js = "javascript:";
  2. js += "var videos = document.getElementsByTagName('video');";
  3. js += "var video_last;";
  4. js += "var video = videos[videos.length-1];";
  5. js += "if (video != undefined && video != video_last) {";
  6. {
  7. js += "video_last = video;";
  8. js += "function video_start() {";
  9. {
  10. js += "_VideoEnabledWebView.notifyVideoStart();";
  11. }
  12. js += "}";
  13. js += "video.addEventListener('play', video_start);";
  14. }
  15. js += "}";
  16. main_wv.loadUrl(js); // main_wv为WebView控件

        忘了介绍,该js脚本在什么时候执行了。这里补充一下,为了使得页面自动播放视频,需要重写一个WebViewClient类,类名可以随你定义,比如“MyWebViewClient”,然后重写public void onPageFinished(WebView view, String url)方法,如下:

  1. @Override
  2. public void onPageFinished(WebView view, String url) {
  3. super.onPageFinished(view, url);
  4. String js = "javascript:";
  5. js += "var videos = document.getElementsByTagName('video');";
  6. js += "var video_last;";
  7. js += "var video = videos[videos.length-1];";
  8. js += "if (video != undefined && video != video_last) {";
  9. {
  10. js += "video_last = video;";
  11. js += "function video_start() {";
  12. {
  13. js += "_VideoEnabledWebView.notifyVideoStart();";
  14. }
  15. js += "}";
  16. js += "video.addEventListener('play', video_start);";
  17. }
  18. js += "}";
  19. main_wv.loadUrl(js); // main_wv为WebView控件
  20. }

        至此,还请记得改

main_wv.setWebViewClient(new WebViewClient()); // main_wv为WebView控件

        为

main_wv.setWebViewClient(new MyWebViewClient()); // main_wv为WebView控件

        这样,在访问网页时,视频就可以自动播放啦。

三、网页自动全屏思路

        网页全屏的实现思路比较复杂,因为Android开发者的初衷是使网页设计者无法通过js的方式直接全屏地播放视频。也就是说,通过js注入的方式无法直接在WebView中实现网页的全屏播放。为什么呢?根据其他人的说法,这是因为Android开发者担心你的手机不小心访问到一个流氓网页,然后该网页直接全屏,使你的手机失控,被它播放的视频霸占许久、不能退出。我想了想,觉得这个理由倒是有些许合理的。因此执行js脚本注入无法直接在WebView中实现网页视频的全屏播放。

        但是网页全屏的实现是完全没有问题的。大体的思路是:重写WebChromeClient和WebView这两个类,通过重写其中的内部方法,在加载完网页后,再调用js脚本注入,进而触发视频的全屏播放。而触发视频的全屏播放的js脚本为:

  1. "javascript:(" +
  2. "function() { " +
  3. " var videos = document.getElementsByTagName('video'); " +
  4. " var video = videos[0]; " +
  5. " if (!document.webkitFullScreen && video.webkitEnterFullscreen) {" +
  6. " video.webkitEnterFullscreen(); " +
  7. " } " +
  8. " })()"

        由于实现的细节很多,再加上我只是简单地研究了一下,所以没法更详细地展开说说了。请大家看后边“全部代码”的章节部分,了解更多细节。

四、手机默认横屏思路

        手机默认横屏的思路实现起来非常简单,简单得不得了,只需要在Manifest.xml这个清单文件中对指定的Activity声明相关的属性即可。例如,用于播放的Activity为MainActivity,那么就这样设置:

  1. <activity android:name=".MainActivity"
  2. android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
  3. android:screenOrientation="landscape"
  4. android:configChanges="orientation|screenSize|keyboardHidden"
  5. android:hardwareAccelerated="true">
  6. activity>

        其中,最关键的两行代码为

  1. android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
  2. android:screenOrientation="landscape"

        上面一行说的是让app在手机上运行时不显示标题栏(这个可以看你个人需求,有的人喜欢留着,有的人喜欢去掉),而下面一行则是实现横屏的开关,landscape指的是风景,意为通过手机横屏的方式欣赏图片中的风景,以尽可能地使你更加清楚地目睹一张横向的风景图。

五、全部代码

        项目的代码目录,其中画横线部分是重点,我从创建项目到生成可运行且有效果的App只改动过这些文件。下面我将每个框中的文件中的代码罗列出来。

        AndroidManifest.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3. package="***.***.******">
  4. <uses-permission android:name="android.permission.INTERNET" />
  5. <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
  6. <application
  7. android:allowBackup="true"
  8. android:icon="@mipmap/ic_launcher"
  9. android:label="@string/app_name"
  10. android:roundIcon="@mipmap/ic_launcher_round"
  11. android:supportsRtl="true"
  12. android:theme="@style/AppTheme">
  13. <activity android:name=".MainActivity"
  14. android:hardwareAccelerated="true"
  15. android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
  16. android:screenOrientation="landscape">
  17. <intent-filter>
  18. <action android:name="android.intent.action.MAIN" />
  19. <category android:name="android.intent.category.LAUNCHER" />
  20. intent-filter>
  21. activity>
  22. application>
  23. manifest>

        MainActivity.java

  1. package ***.***.***;
  2. import android.annotation.SuppressLint;
  3. import android.app.Activity;
  4. import android.content.Context;
  5. import android.content.Intent;
  6. import android.net.ConnectivityManager;
  7. import android.net.NetworkInfo;
  8. import android.os.Bundle;
  9. import android.view.ViewGroup;
  10. import android.webkit.WebSettings;
  11. import android.webkit.WebView;
  12. import android.webkit.WebViewClient;
  13. import android.widget.LinearLayout;
  14. import android.widget.RelativeLayout;
  15. public class MainActivity extends Activity {
  16. VideoEnabledWebView mainWebView;
  17. RelativeLayout mainNonVideoRelativeLayout;
  18. ViewGroup mainVideoLayout;
  19. @Override
  20. protected void onCreate(Bundle savedInstanceState) {
  21. super.onCreate(savedInstanceState);
  22. initView(); // initialize ui components
  23. setWebView(); // set webview's settings
  24. loadVideoUrl(); // load video url
  25. }
  26. private void initView() {
  27. setContentView(R.layout.activity_main);
  28. mainNonVideoRelativeLayout = (RelativeLayout) findViewById(R.id.main_rl_non_video);
  29. mainVideoLayout = (ViewGroup)findViewById(R.id.main_rl_video);
  30. }
  31. @SuppressLint("SetJavaScriptEnabled")
  32. private void setWebView() {
  33. // create a webview instance
  34. mainWebView = new VideoEnabledWebView(this);
  35. mainWebView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
  36. // add the webview instance to the main layout
  37. mainNonVideoRelativeLayout.addView(mainWebView);
  38. // set general settings of webview
  39. WebSettings settings = mainWebView.getSettings();
  40. settings.setAllowFileAccess(true);
  41. settings.setBuiltInZoomControls(false);
  42. settings.setJavaScriptEnabled(true);
  43. settings.setBuiltInZoomControls(false);
  44. // create a WebChromeClient instance and use it to set the webview
  45. VideoEnabledWebChromeClient videoEnabledWebChromeClient = new VideoEnabledWebChromeClient(mainNonVideoRelativeLayout, mainVideoLayout,null, mainWebView);
  46. mainWebView.setWebChromeClient(videoEnabledWebChromeClient);
  47. // create a WebViewClient for webview
  48. mainWebView.setWebViewClient(new WebViewClient(){
  49. @Override
  50. public void onPageFinished(WebView view, String url) {
  51. super.onPageFinished(view, url);
  52. // execute a javascript to automatically play the video
  53. String js = "javascript:";
  54. js += "var videos = document.getElementsByTagName('video');";
  55. js += "var video_last;";
  56. js += "var video = videos[videos.length-1];";
  57. js += "if (video != undefined && video != video_last) {";
  58. {
  59. js += "video_last = video;";
  60. js += "function video_start() {";
  61. {
  62. js += "_VideoEnabledWebView.notifyVideoStart();";
  63. }
  64. js += "}";
  65. js += "video.addEventListener('play', video_start);";
  66. }
  67. js += "}";
  68. mainWebView.loadUrl(js);
  69. }
  70. });
  71. }
  72. private void loadVideoUrl() {
  73. mainWebView.loadUrl("https://******"); // your url that contains the video
  74. }
  75. }

        activity_main.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:tools="http://schemas.android.com/tools"
  4. android:layout_width="match_parent"
  5. android:layout_height="match_parent"
  6. tools:context=".MainActivity">
  7. <RelativeLayout
  8. android:id="@+id/main_rl_non_video"
  9. android:layout_width="match_parent"
  10. android:layout_height="match_parent" >
  11. RelativeLayout>
  12. <RelativeLayout
  13. android:id="@+id/main_rl_video"
  14. android:layout_width="match_parent"
  15. android:layout_height="match_parent" >
  16. RelativeLayout>
  17. androidx.constraintlayout.widget.ConstraintLayout>

        VideoEnabledWebChromeClient.java

  1. package ***.***.***;
  2. import android.media.MediaPlayer;
  3. import android.view.SurfaceView;
  4. import android.view.View;
  5. import android.view.ViewGroup;
  6. import android.webkit.WebChromeClient;
  7. import android.widget.FrameLayout;
  8. public class VideoEnabledWebChromeClient extends WebChromeClient implements MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener {
  9. public interface ToggledFullscreenCallback {
  10. void toggledFullscreen(boolean fullscreen);
  11. }
  12. private View activityNonVideoView;
  13. private ViewGroup activityVideoView;
  14. private View loadingView;
  15. private VideoEnabledWebView webView;
  16. // Indicates if the video is being displayed using a custom view (typically full-screen)
  17. private boolean isVideoFullscreen;
  18. private FrameLayout videoViewContainer;
  19. private CustomViewCallback videoViewCallback;
  20. private ToggledFullscreenCallback toggledFullscreenCallback;
  21. /**
  22. * Never use this constructor alone.
  23. * This constructor allows this class to be defined as an inline inner class in which the user can override methods
  24. */
  25. @SuppressWarnings("unused")
  26. public VideoEnabledWebChromeClient() {
  27. }
  28. /**
  29. * Builds a video enabled WebChromeClient.
  30. * @param activityNonVideoView A View in the activity's layout that contains every other view that should be hidden when the video goes full-screen.
  31. * @param activityVideoView A ViewGroup in the activity's layout that will display the video. Typically you would like this to fill the whole layout.
  32. */
  33. @SuppressWarnings("unused")
  34. public VideoEnabledWebChromeClient(View activityNonVideoView, ViewGroup activityVideoView) {
  35. this.activityNonVideoView = activityNonVideoView;
  36. this.activityVideoView = activityVideoView;
  37. this.loadingView = null;
  38. this.webView = null;
  39. this.isVideoFullscreen = false;
  40. }
  41. /**
  42. * Builds a video enabled WebChromeClient.
  43. * @param activityNonVideoView A View in the activity's layout that contains every other view that should be hidden when the video goes full-screen.
  44. * @param activityVideoView A ViewGroup in the activity's layout that will display the video. Typically you would like this to fill the whole layout.
  45. * @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.
  46. */
  47. @SuppressWarnings("unused")
  48. public VideoEnabledWebChromeClient(View activityNonVideoView, ViewGroup activityVideoView, View loadingView) {
  49. this.activityNonVideoView = activityNonVideoView;
  50. this.activityVideoView = activityVideoView;
  51. this.loadingView = loadingView;
  52. this.webView = null;
  53. this.isVideoFullscreen = false;
  54. }
  55. /**
  56. * Builds a video enabled WebChromeClient.
  57. * @param activityNonVideoView A View in the activity's layout that contains every other view that should be hidden when the video goes full-screen.
  58. * @param activityVideoView A ViewGroup in the activity's layout that will display the video. Typically you would like this to fill the whole layout.
  59. * @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.
  60. * @param webView The owner VideoEnabledWebView. Passing it will enable the VideoEnabledWebChromeClient to detect the HTML5 video ended event and exit full-screen.
  61. * 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).
  62. */
  63. @SuppressWarnings("unused")
  64. public VideoEnabledWebChromeClient(View activityNonVideoView, ViewGroup activityVideoView, View loadingView, VideoEnabledWebView webView) {
  65. this.activityNonVideoView = activityNonVideoView;
  66. this.activityVideoView = activityVideoView;
  67. this.loadingView = loadingView;
  68. this.webView = webView;
  69. this.isVideoFullscreen = false;
  70. }
  71. /**
  72. * Indicates if the video is being displayed using a custom view (typically full-screen)
  73. * @return true it the video is being displayed using a custom view (typically full-screen)
  74. */
  75. public boolean isVideoFullscreen() {
  76. return isVideoFullscreen;
  77. }
  78. /**
  79. * Set a callback that will be fired when the video starts or finishes displaying using a custom view (typically full-screen)
  80. * @param callback A VideoEnabledWebChromeClient.ToggledFullscreenCallback callback
  81. */
  82. @SuppressWarnings("unused")
  83. public void setOnToggledFullscreen(ToggledFullscreenCallback callback) {
  84. this.toggledFullscreenCallback = callback;
  85. }
  86. @Override
  87. public void onShowCustomView(View view, CustomViewCallback callback) {
  88. if (view instanceof FrameLayout) {
  89. // A video wants to be shown
  90. FrameLayout frameLayout = (FrameLayout) view;
  91. View focusedChild = frameLayout.getFocusedChild();
  92. // Save video related variables
  93. this.isVideoFullscreen = true;
  94. this.videoViewContainer = frameLayout;
  95. this.videoViewCallback = callback;
  96. // Hide the non-video view, add the video view, and show it
  97. activityNonVideoView.setVisibility(View.INVISIBLE);
  98. activityVideoView.addView(videoViewContainer, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
  99. activityVideoView.setVisibility(View.VISIBLE);
  100. if (focusedChild instanceof android.widget.VideoView) {
  101. // android.widget.VideoView (typically API level <11)
  102. android.widget.VideoView videoView = (android.widget.VideoView) focusedChild;
  103. // Handle all the required events
  104. videoView.setOnPreparedListener(this);
  105. videoView.setOnCompletionListener(this);
  106. videoView.setOnErrorListener(this);
  107. } else {
  108. // Other classes, including:
  109. // - android.webkit.HTML5VideoFullScreen$VideoSurfaceView, which inherits from android.view.SurfaceView (typically API level 11-18)
  110. // - android.webkit.HTML5VideoFullScreen$VideoTextureView, which inherits from android.view.TextureView (typically API level 11-18)
  111. // - com.android.org.chromium.content.browser.ContentVideoView$VideoSurfaceView, which inherits from android.view.SurfaceView (typically API level 19+)
  112. // Handle HTML5 video ended event only if the class is a SurfaceView
  113. // Test case: TextureView of Sony Xperia T API level 16 doesn't work fullscreen when loading the javascript below
  114. if (webView != null && webView.getSettings().getJavaScriptEnabled() && focusedChild instanceof SurfaceView) {
  115. // Run javascript code that detects the video end and notifies the Javascript interface
  116. String js = "javascript:";
  117. js += "var _ytrp_html5_video_last;";
  118. js += "var _ytrp_html5_video = document.getElementsByTagName('video')[0];";
  119. js += "if (_ytrp_html5_video != undefined && _ytrp_html5_video != _ytrp_html5_video_last) {";
  120. {
  121. js += "_ytrp_html5_video_last = _ytrp_html5_video;";
  122. js += "function _ytrp_html5_video_ended() {";
  123. {
  124. js += "_VideoEnabledWebView.notifyVideoEnd();"; // Must match Javascript interface name and method of VideoEnableWebView
  125. }
  126. js += "}";
  127. js += "_ytrp_html5_video.addEventListener('ended', _ytrp_html5_video_ended);";
  128. }
  129. js += "}";
  130. webView.loadUrl(js);
  131. }
  132. }
  133. // Notify full-screen change
  134. if (toggledFullscreenCallback != null) {
  135. toggledFullscreenCallback.toggledFullscreen(true);
  136. }
  137. }
  138. }
  139. @Override
  140. // Available in API level 14+, deprecated in API level 18+
  141. public void onShowCustomView(View view, int requestedOrientation, CustomViewCallback callback) {
  142. onShowCustomView(view, callback);
  143. }
  144. @Override
  145. // This method should be manually called on video end in all cases because it's not always called automatically.
  146. // This method must be manually called on back key press (from this class' onBackPressed() method).
  147. public void onHideCustomView() {
  148. if (isVideoFullscreen) {
  149. // Hide the video view, remove it, and show the non-video view
  150. activityVideoView.setVisibility(View.INVISIBLE);
  151. activityVideoView.removeView(videoViewContainer);
  152. activityNonVideoView.setVisibility(View.VISIBLE);
  153. // Call back (only in API level <19, because in API level 19+ with chromium webview it crashes)
  154. if (videoViewCallback != null && !videoViewCallback.getClass().getName().contains(".chromium.")) {
  155. videoViewCallback.onCustomViewHidden();
  156. }
  157. // Reset video related variables
  158. isVideoFullscreen = false;
  159. videoViewContainer = null;
  160. videoViewCallback = null;
  161. // Notify full-screen change
  162. if (toggledFullscreenCallback != null) {
  163. toggledFullscreenCallback.toggledFullscreen(false);
  164. }
  165. }
  166. }
  167. @Override
  168. // Video will start loading
  169. public View getVideoLoadingProgressView() {
  170. if (loadingView != null) {
  171. loadingView.setVisibility(View.VISIBLE);
  172. return loadingView;
  173. } else {
  174. return super.getVideoLoadingProgressView();
  175. }
  176. }
  177. @Override
  178. // Video will start playing, only called in the case of android.widget.VideoView (typically API level <11)
  179. public void onPrepared(MediaPlayer mp) {
  180. if (loadingView != null) {
  181. loadingView.setVisibility(View.GONE);
  182. }
  183. }
  184. @Override
  185. // Video finished playing, only called in the case of android.widget.VideoView (typically API level <11)
  186. public void onCompletion(MediaPlayer mp) {
  187. onHideCustomView();
  188. }
  189. @Override
  190. // Error while playing video, only called in the case of android.widget.VideoView (typically API level <11)
  191. public boolean onError(MediaPlayer mp, int what, int extra) {
  192. return false; // By returning false, onCompletion() will be called
  193. }
  194. /**
  195. * Notifies the class that the back key has been pressed by the user.
  196. * 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.
  197. * @return Returns true if the event was handled, and false if was not (video view is not visible)
  198. */
  199. @SuppressWarnings("unused")
  200. public boolean onBackPressed() {
  201. if (isVideoFullscreen) {
  202. onHideCustomView();
  203. return true;
  204. } else {
  205. return false;
  206. }
  207. }
  208. }

        VideoEnabledWebView.java

  1. package ***.***.***;
  2. import android.annotation.SuppressLint;
  3. import android.content.Context;
  4. import android.os.Handler;
  5. import android.os.Looper;
  6. import android.util.AttributeSet;
  7. import android.webkit.WebChromeClient;
  8. import android.webkit.WebView;
  9. import java.util.Map;
  10. public class VideoEnabledWebView extends WebView {
  11. public class JavascriptInterface {
  12. @android.webkit.JavascriptInterface
  13. @SuppressWarnings("unused")
  14. // Must match Javascript interface method of VideoEnabledWebChromeClient
  15. public void notifyVideoEnd() {
  16. // This code is not executed in the UI thread, so we must force that to happen
  17. new Handler(Looper.getMainLooper()).post(new Runnable() {
  18. @Override
  19. public void run() {
  20. if (videoEnabledWebChromeClient != null) {
  21. videoEnabledWebChromeClient.onHideCustomView();
  22. }
  23. }
  24. });
  25. }
  26. @android.webkit.JavascriptInterface
  27. @SuppressWarnings("unused")
  28. // Must match Javascript interface method of VideoEnabledWebChromeClient
  29. public void notifyVideoStart() {
  30. // This code is not executed in the UI thread, so we must force that to happen
  31. new Handler(Looper.getMainLooper()).post(new Runnable() {
  32. @Override
  33. public void run() {
  34. loadUrl("javascript:(" +
  35. "function() { " +
  36. " var videos = document.getElementsByTagName('video'); " +
  37. " var video = videos[0]; " +
  38. " if (!document.webkitFullScreen && video.webkitEnterFullscreen) {" +
  39. " video.webkitEnterFullscreen(); " +
  40. " } " +
  41. " })()");
  42. }
  43. });
  44. }
  45. }
  46. private VideoEnabledWebChromeClient videoEnabledWebChromeClient;
  47. private boolean addedJavascriptInterface;
  48. @SuppressWarnings("unused")
  49. public VideoEnabledWebView(Context context) {
  50. super(context);
  51. addedJavascriptInterface = false;
  52. }
  53. @SuppressWarnings("unused")
  54. public VideoEnabledWebView(Context context, AttributeSet attrs) {
  55. super(context, attrs);
  56. addedJavascriptInterface = false;
  57. }
  58. @SuppressWarnings("unused")
  59. public VideoEnabledWebView(Context context, AttributeSet attrs, int defStyle) {
  60. super(context, attrs, defStyle);
  61. addedJavascriptInterface = false;
  62. }
  63. /**
  64. * Indicates if the video is being displayed using a custom view (typically full-screen)
  65. *
  66. * @return true it the video is being displayed using a custom view (typically full-screen)
  67. */
  68. @SuppressWarnings("unused")
  69. public boolean isVideoFullscreen() {
  70. return videoEnabledWebChromeClient != null && videoEnabledWebChromeClient.isVideoFullscreen();
  71. }
  72. /**
  73. * Pass only a VideoEnabledWebChromeClient instance.
  74. */
  75. @Override
  76. @SuppressLint("SetJavaScriptEnabled")
  77. public void setWebChromeClient(WebChromeClient client) {
  78. getSettings().setJavaScriptEnabled(true);
  79. if (client instanceof VideoEnabledWebChromeClient) {
  80. this.videoEnabledWebChromeClient = (VideoEnabledWebChromeClient) client;
  81. }
  82. super.setWebChromeClient(client);
  83. }
  84. @Override
  85. public void loadData(String data, String mimeType, String encoding) {
  86. addJavascriptInterface();
  87. super.loadData(data, mimeType, encoding);
  88. }
  89. @Override
  90. public void loadDataWithBaseURL(String baseUrl, String data, String mimeType, String encoding, String historyUrl) {
  91. addJavascriptInterface();
  92. super.loadDataWithBaseURL(baseUrl, data, mimeType, encoding, historyUrl);
  93. }
  94. @Override
  95. public void loadUrl(String url) {
  96. super.loadUrl(url);
  97. addJavascriptInterface();
  98. }
  99. @Override
  100. public void loadUrl(String url, Map additionalHttpHeaders) {
  101. addJavascriptInterface();
  102. super.loadUrl(url, additionalHttpHeaders);
  103. }
  104. @SuppressLint("AddJavascriptInterface")
  105. private void addJavascriptInterface() {
  106. if (!addedJavascriptInterface) {
  107. // Add javascript interface to be called when the video ends (must be done before page load)
  108. // Must match Javascript interface name of VideoEnabledWebChromeClient
  109. addJavascriptInterface(new JavascriptInterface(), "_VideoEnabledWebView");
  110. addedJavascriptInterface = true;
  111. }
  112. }
  113. }

六、效果

        打开App之后,经过2s的时间(对于个人而言,2s是可接受的等待时间)直接视频全屏播放

        但我发现url有时候不是特别稳定,所以有时候看不了,并建议使用电脑端访问。

七、参考资料

1.如何在android WebView中全屏播放HTML5视频?

2.android webview播放视频自动全屏

八、声明

上述代码仅限个人的学习使用,请勿用于商业用途,请勿非法使用,谢谢。

标签:
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

在线投稿:投稿 站长QQ:1888636

后台-插件-广告管理-内容页尾部广告(手机)
关注我们

扫一扫关注我们,了解最新精彩内容

搜索
排行榜