Android WebView not stopping after user presses back

后端 未结 6 1698
傲寒
傲寒 2021-01-31 03:18

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

相关标签:
6条回答
  • 2021-01-31 03:28

    In activity's onDestroy() do:

    @Override
    protected void onDestroy() {
        super.onDestroy();
        webView.destroy();
    }
    
    0 讨论(0)
  • 2021-01-31 03:30

    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();
    }
    
    0 讨论(0)
  • 2021-01-31 03:32

    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().

    0 讨论(0)
  • 2021-01-31 03:38

    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)

    0 讨论(0)
  • 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();
    }
    
    0 讨论(0)
  • 2021-01-31 03:49

    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

    0 讨论(0)
提交回复
热议问题