How to stop youtube video playing in Android webview?

Droid picture Droid · May 10, 2011 · Viewed 52.9k times · Source

How can I stop a YouTube video which is played in my webview? When I click on the back button the video doesn't stop and instead continues in the background.

Code:

webView = (WebView) findViewById(R.id.webview); 
webView.getSettings().setPluginsEnabled(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(false); 
webView.getSettings().setSupportZoom(false);
webView.loadData(myUrl,"text/html", "utf-8");

Answer

Andrew Thompson picture Andrew Thompson · Jun 3, 2011

See the following post about WebView threads never stopping

Essentially you'll need to call the WebView's onPause method from your own Activity's onPause method.

The only trick with this is that you cannot call the WebView's onPause method directly because it is hidden. Therefore you will need to call it indirectly via reflection. The following code should get you started on setting up your own Activity's onPause method:

@Override
public void onPause() {
    super.onPause();

    try {
        Class.forName("android.webkit.WebView")
                .getMethod("onPause", (Class[]) null)
                            .invoke(webview, (Object[]) null);

    } catch(ClassNotFoundException cnfe) {
        ...
    } catch(NoSuchMethodException nsme) {
        ...
    } catch(InvocationTargetException ite) {
        ...
    } catch (IllegalAccessException iae) {
        ...
    }
}

Note that the variable 'webview' in the try block above is a private instance variable for the class and is assigned to in the Activity's onCreate method.