How to stop youtube video playing in Android webview?

AndroidVideoWebviewYoutube

Android Problem Overview


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");

Android Solutions


Solution 1 - Android

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.

Solution 2 - Android

Solution: 1 - After spending lot of time, I got the conclusion to pause the video which is playing with WebView <iframe> concept of HTML.

Just override the onPause() method on Activity or Fragment whereever you used WebView, and call it. It works for me.

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

@Override
public void onResume() {
    super.onResume();
    mWebView.onResume();
}

Solution: 2 - If above solution doesn't work for you then you can force WebView to load a non existent html file.

mWebview.loadUrl("file:///android_asset/nonexistent.html");

Solution 3 - Android

you also have to implement the onResume() method or second time it won't work

@Override
public void onResume()
{
    super.onResume();
    webView.onResume();
}

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

Solution 4 - Android

The above solution failed for me on Samsung Galaxy S with Android 2.3.3. But I made success trying the below workaround:

	webview.loadUrl("file:///android_asset/nonexistent.html");

I am forcing the webview to load a non existent html file. This seems to be forcing the webview to clean things up.

Solution 5 - Android

Try this:

@Override
public void onPause() {
    super.onPause();
    myWebView.onPause();
    myWebView.pauseTimers();
}

@Override
public void onResume() {
    super.onResume();
    myWebView.resumeTimers();
    myWebView.onResume();
}


@Override
protected void onDestroy() {
    myWebView.destroy();
    myWebView = null;
    super.onDestroy();
}

Solution 6 - Android

And here's my personal favourite:

@Override
protected void onPause() {
    super.onPause();
    if (isFinishing()) {
        webView.loadUrl("about:blank");
    } else {
        webView.onPause();
        webView.pauseTimers();
    }
}

@Override
protected void onResume() {
    super.onResume();
    webView.resumeTimers();
    webView.onResume();
}

It pauses the webview if the view is only paused, but clears it when the activity is finished.

This requires at least Android 3.0 - API 11 (Honeycomb)

Solution 7 - Android

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
	// TODO Auto-generated method stub
	if(keyCode==event.KEYCODE_BACK)
	{
		mWebview.loadUrl("");
		mWebview.stopLoading();
		
		finish();
		
	}
	return super.onKeyDown(keyCode, event);
}

it works

Solution 8 - Android

The above approach did not work for me, one which worked for me is :

@Override
protected void onPause() {
    super.onPause();
    ((AudioManager)getSystemService(
            Context.AUDIO_SERVICE)).requestAudioFocus(
                    new OnAudioFocusChangeListener() {
                        @Override
                        public void onAudioFocusChange(int focusChange) {}
                    }, AudioManager.STREAM_MUSIC, 
                    AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
}

Solution 9 - Android

Webview.loadUrl("about:blank");

it is also working

Solution 10 - Android

After having encountered this problem it seems that onPause might not be doing anything... for me it was not stopping whatever was playing in background.

so my code now looks like

@Override
protected void onPause() {
	mWebView.onPause();
	super.onPause();
}

@Override
protected void onResume() {
	mWebView.onResume();
	super.onResume();
}

@Override
protected void onSaveInstanceState(Bundle outState) {
	mWebView.saveState(outState);
	super.onSaveInstanceState(outState);
}

@Override
protected void onDestroy() {
	mWebView.destroy();
	mWebView = null;		
	super.onDestroy();
}

Hope it helps anyone with the same problem as me

Solution 11 - Android

you can try this

webView.loadUrl("javascript:document.location=document.location");

if the page which is loading is one you can edit then you can write a javascript method which stop the audio and call when you want to stop like.

Javascript function

 function stopAudio(){
    audios=document.querySelectorAll('audio');
      for(i=0;i<audios.length;i++){
       audios[i].stop();
      }
    }

From Andorid Call this method

webView.loadUrl("javascript:stopAudio()");

if the page is not editable by you the you can inject the js code

   @Override
   public void onPageFinished(WebView view, String url) {
      super.onPageFinished(view, url);

      injectScriptFile(view, "js/script.js"); 

   }

How to Inject See Here in Detail

Solution 12 - Android

Based on @sommesh's answer:

override fun onPause() {
    super.onPause()

    val audioManager = getSystemService(Context.AUDIO_SERVICE) as AudioManager

    if (Utils.hasOreoSDK26()) {
        val audioAttributes = AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_MEDIA)
                .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                .build()
        val audioFocusRequest = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT)
                .setAudioAttributes(audioAttributes)
                .setAcceptsDelayedFocusGain(true)
                .setWillPauseWhenDucked(true)
                .setOnAudioFocusChangeListener(
                        { focusChange -> Timber.i(">>> Focus change to : %d", focusChange) },
                        Handler())
                .build()
        audioManager.requestAudioFocus(audioFocusRequest)
    } else {
        audioManager.requestAudioFocus({ }, AudioManager.STREAM_MUSIC,
                AudioManager.AUDIOFOCUS_GAIN_TRANSIENT)
    }
}

Solution 13 - Android

This works for me.

@Override
protected void onPause() {
	super.onPause();
	if (wViewCampaign != null){
		wViewCampaign.stopLoading(); 
		wViewCampaign.loadUrl("");
		wViewCampaign.reload();
		wViewCampaign = null;
	}
}

Solution 14 - Android

You can do it by using the method onPause() of the of WebView when is executed the method onPause()of your Activity :

@override
public void onPause() {
        super.onPause();
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
          webview.onPause();
        }
}
  • works for API >= 11 (Honeycomb)

Solution 15 - Android

I tried all above answer , but most of them not work for me. so i just write my own solution which works fine in all type of media playing in webview

 String lastUrl = "";
 @Override
    public void onPause() {
        super.onPause();
        lastUrl =  webView.getUrl();
        webView.loadUrl("");
    }

    @Override
    protected void onResume() {
        super.onResume();
        webView.loadUrl(lastUrl);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        webView = null;
    }

Solution 16 - Android

This is what finally worked after trying each and every code provided on this page. Uff!

@Override
protected void onPause() {
    super.onPause();
    if (mWebView != null) {
        mWebView.stopLoading();
        mWebView.reload();
    }
}

@Override
protected void onResume() {
    super.onResume();
}

Solution 17 - Android

In my situation, the player keep running after the WebView is "onPause." So I check if the WebView is attached to the windows before playing video or music.

It is JavaScriptInterface method for checking WebView's "isAttachedToWindow()" return true/false.

(And I didn't forget to call onPause/onResume in Activity/Fragment.)

Solution 18 - Android

This code works perfect for me.

 @Override protected void onPause() {
	super.onPause();
	wv.onPause();
	wv.pauseTimers();
}
	@Override protected void onResume() {
	super.onResume();
	wv.resumeTimers();
	wv.onResume();
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDroidView Question on Stackoverflow
Solution 1 - AndroidAndrew ThompsonView Answer on Stackoverflow
Solution 2 - AndroidVishesh ChandraView Answer on Stackoverflow
Solution 3 - AndroidCLuceraView Answer on Stackoverflow
Solution 4 - AndroiddangelView Answer on Stackoverflow
Solution 5 - AndroidThiagoView Answer on Stackoverflow
Solution 6 - AndroidBjörn KechelView Answer on Stackoverflow
Solution 7 - Androiduser3437083View Answer on Stackoverflow
Solution 8 - AndroidsommeshView Answer on Stackoverflow
Solution 9 - AndroidSanghwa JungView Answer on Stackoverflow
Solution 10 - AndroidKrzysztof DubrowskiView Answer on Stackoverflow
Solution 11 - AndroidAzmat Karim KhanView Answer on Stackoverflow
Solution 12 - AndroidrayworksView Answer on Stackoverflow
Solution 13 - AndroidManuel SchmitzbergerView Answer on Stackoverflow
Solution 14 - AndroidJorgesysView Answer on Stackoverflow
Solution 15 - AndroidAbhishek GargView Answer on Stackoverflow
Solution 16 - AndroidRamesh SeerviView Answer on Stackoverflow
Solution 17 - Androidhsu.twView Answer on Stackoverflow
Solution 18 - AndroidRoberto LópezView Answer on Stackoverflow