我对 Android 4.0+ 上的 HTML5 视频有以下发现。
为了执行这些测试,我制作了一个沙盒应用程序,其中包含一个保存在 /assets 中的 HTML 页面。
HTML:
<!DOCTYPE html>
<html>
<head>
<title>HTML5 Video Test</title>
</head>
<body>
<video preload="metadata"><source src="http://www.w3schools.com/html/movie.mp4" type="video/mp4"></video>
<script>
var myvideo = document.getElementsByTagName('video')[0];
myvideo.addEventListener('loadeddata', function() {
console.log("** RECEIVED loadeddata **");
myvideo.play();//this first play is needed for Android 4.1+
}, false);
myvideo.addEventListener('canplaythrough', function() {
console.log("** RECEIVED canplaythrough **");
myvideo.play();//this second play is needed for Android 4.0 only
}, false);
</script>
</body>
</html>
JAVA:(“/assets/html5video.html”)
private WebView mWebView;
private ProgressBar mProgressBar;
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.videotest);
// progress bar
mProgressBar = (ProgressBar) findViewById(R.id.videotest_progressbar);
mProgressBar.setProgress(0);
mProgressBar.setVisibility(View.VISIBLE);
// webview
mWebView = (WebView) findViewById(R.id.videotest_webview);
mWebView.getSettings().setJavaScriptEnabled(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
{
//NOTE: this is required only for Android 4.2.2+
mWebView.getSettings().setMediaPlaybackRequiresUserGesture(false);
}
mWebView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
Log.i(TAG, "Progress = "+progress);
mProgressBar.setProgress(progress);
}
});
mWebView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(TestActivity.this, "Problem loading webpage", Toast.LENGTH_LONG).show();
mProgressBar.setVisibility(View.GONE);
}
public void onPageFinished(WebView view, String url) {
mProgressBar.setVisibility(View.GONE);
}
});
}
@Override
protected void onResume() {
super.onResume();
mWebView.loadUrl("file:///android_asset/html5video.html");
}
安卓 4.0.3 注意
我一直遇到烦人的异常java.lang.Throwable: EventHub.removeMessages(int what = 107) is not supported before the WebViewCore is set up.
幸运的是,它并没有影响视频播放。