Background:
The project requirement is to go to the page to automatically play audio or video (non-local resources) when the page closes when the audio or video is turned off. Now the implementation of the situation is: the auto-play function on some phones can automatically play and have sound, and some phones also play but no sound, when the user clicks or generates a trigger condition will have a sound; exit close current activity, audio or video is not turned off, still playing.
Workaround:
1. Turn off audio or video when activity exits
Rewrite the activity's OnDestroy () method to add the Webview.destroy () method to the method.
@Overrideprotected void onDestroy() { super.onDestroy(); //为了使WebView退出时音频或视频关闭 webView.destroy();}
2. Audio or video auto-play
Write an AutoPlay method that executes the method in the activity's OnCreate () method, Webviewclient, onpagefinished ().
@Overridepublic void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.webview_activity); ...... autoPlay();}private class MyWebViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { ...... } @Override public void onPageFinished(WebView view, String url) { ...... autoPlay(); ...... } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { ...... }}/** * 使视频或音频自动播放,默认播放第一条 */public void autoPlay() { //音频自动播放js方法 String audioJs = "javascript: var v = document.getElementsByTagName(‘audio‘); v[0].play();"; webView.loadUrl(audioJs); //视频自动播放js方法 String videoJs = "javascript: var v = document.getElementsByTagName(‘video‘); v[0].play();"; webView.loadUrl(videoJs);}
Insufficient:
如果WebView中既有音频也有视频的话,会导致它们同时播放;如果音频播放过程中要播放视频,音频要暂停,视频播放完音频要接着播放;还有一些更加复杂的场景这个并没有实现。
The above is only personal opinion, there is a problem please give us a lot of advice.
WebView midrange video auto play and stop playing when exiting