Reputation:
In my android application I want to open a webpage in a WebView. A webpage which i want to open also contains video. To achieve this functionality,I used WebChromeClient in my application. The problem is that, onBackPressed() of this activity, some videos don't get stopped and they keep playing in background, though my WebView activity is finished. I don't know why this happens. I tried various codes, but couldn't solve this problem. Some videos stop automatically, but some keeps on playing in background. How to solve this issue ?
here is my code
@Override
public void onBackPressed() {
if (myWebView.canGoBack()) {
myWebView.goBack();
} else {
super.onBackPressed();
}
}
Upvotes: 3
Views: 766
Reputation: 819
You can pause the webview by using this:-
public void pauseVideo()
{
try {
Class.forName("android.webkit.WebView")
.getMethod("onPause", (Class[]) null)
.invoke(myWebView, (Object[]) null);
} catch(ClassNotFoundException cnfe) {
...
} catch(NoSuchMethodException nsme) {
...
} catch(InvocationTargetException ite) {
...
} catch (IllegalAccessException iae) {
...
}
}
Then in onBackpressed you can invoke this method like this:-
@Override
public void onBackPressed() {
if (myWebView.canGoBack()) {
pauseVideo();
myWebView.goBack();
} else {
super.onBackPressed();
}
}
Upvotes: 0
Reputation: 24848
Ref - 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()
.
There's also pauseTimers()
, which affects all of the WebViews within your application:
Pauses all layout, parsing, and JavaScript timers for all WebViews. This is a global requests, not restricted to just this WebView. This can be useful if the application has been paused.
Upvotes: 0
Reputation: 66
use to on Back pressed this code
@Override
public void onBackPressed() {
mWebView.stopLoading();
mWebView.removeAllViews();
mWebView.destroy();
mWebView = null;
finish();
super.onBackPressed();
}
Upvotes: 3