是否可以检查 WebView 目前是否正在播放视频,如果是,则获取要下载的该视频的 http://... .mp4/ URL?
我已经尝试过这段代码:
public void onLoadResource(WebView view, final String url){
super.onLoadResource(view, url);
if(url.endsWith(".mp4") & !url.contains(".jpg") & !url.contains(".png")){
AlertDialog.Builder video_downloaden = new AlertDialog.Builder(SearchActivity.this);
video_downloaden.setTitle("Video downloaden?");
video_downloaden.setMessage("Download Video?");
video_downloaden.setPositiveButton("YES", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
DownloadManager.Request request_video = new DownloadManager.Request(Uri.parse(url));
request_video.allowScanningByMediaScanner();
request_video.setVisibleInDownloadsUi(false);
DownloadManager downloadManager2 = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
request_video.setDestinationInExternalFilesDir(getApplicationContext(), DIRECTORY_DOWNLOADS, File.separator + ".Videos" + File.separator + "video" + video_number);
downloadManager2.enqueue(request_video);
Toast.makeText(SearchActivity.this,"Download started",Toast.LENGTH_LONG).show();
}
});
video_downloaden.setNegativeButton("NO", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
video_downloaden.show();
}
}
但与onLoadResource()
AlertDialog 一直显示,但下载并不每次都有效...
所以我的问题是,是否还有其他机会检查 WebView 是否正在播放视频并获取视频 url?
您可以使用 JavaScript 检测视频是否正在播放。
-
创建一个.js
文件在assets
目录并声明一个 JavaScript 函数和 jQuery,如下所示:
$("video").on("play", function() {
//You can call JavaScriptInterface here.
});
-
插入这个.js
包含视频的网页中的文件。我插入了.js
归档时onPageFinished
叫做。
view?.context?.assets?.let {
val inputStream: InputStream = it.open(scriptFile)
val buffer = ByteArray(inputStream.available())
inputStream.read(buffer)
inputStream.close()
val encoded = Base64.encodeToString(buffer, Base64.NO_WRAP)
view.loadUrl("javascript:(function() {" +
"var parent = document.getElementsByTagName('head').item(0);" +
"var script = document.createElement('script');" +
"script.type = 'text/javascript';" +
"script.innerHTML = window.atob('$encoded');" +
"parent.appendChild(script)" +
"})()")
如果您不熟悉 Kotlin,请查看此参考资料:Android Web-View:将本地 Javascript 文件注入远程网页
-
完毕!如果你使用JavaScriptInterface
,你可以做任何你想做的事,就像这样。
class WebScriptInterface(val button: View) {
@JavascriptInterface
fun hideFloatingButton() {
if (button.visibility == View.VISIBLE) {
button.visibility = View.GONE
}
}
}
Set webView
use JavaScriptInterface
.
webView.addJavascriptInterface
(WebScriptInterface(binding.floatBrowserCollect), "App")
然后打电话。
$("video").on("play", function() {
App.hideFloatingButton()
});
我希望它可以帮助你。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)