I am playing a YouTube video inside a WebView. I am able to play it, but when the person leaves the screen, I am not able to stop the audio from playing.
I tried various
In activity's onDestroy()
do:
@Override
protected void onDestroy() {
super.onDestroy();
webView.destroy();
}
try this, hope it helps:
@Override
public void onPause() {
myWebView.onPause();
myWebView.pauseTimers();
super.onPause();
}
@Override
public void onResume() {
super.onResume();
myWebView.resumeTimers();
myWebView.onResume();
}
@Override
protected void onDestroy() {
myWebView.destroy();
myWebView = null;
super.onDestroy();
}
Taken from https://stackoverflow.com/a/17690221/3032209:
You should call through to the WebView's onPause() and onResume() from your Activity's onPause() and onResume(), respectively.
Pauses any extra processing associated with this WebView and its associated DOM, plugins, JavaScript etc. For example, if this WebView is taken offscreen, this could be called to reduce unnecessary CPU or network traffic. When this WebView is again "active", call onResume().
You can do it using the method onPause()
of your Activity
:
@override
public void onPause() {
super.onPause();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
webview.onPause();
}
}
adding a validation for use in API >= 11 (Honeycomb)
Nothing worked for me in some or all devices. This is the exact solution I guess. Worked for me well.
How to stop youtube video playing in Android webview?
alternatively for API >= 11 you can use _webview.onPause(); on the activity's / fragment's onPause
public void onPause() {
// TODO Auto-generated method stub
super.onPause();
_webview.onPause();
}
You should call:
webView.loadUrl("about:blank");
It will destroy all audio/video as well as Javasript objects and stop all running functions on webview