如何停止在Android webview 中播放youtube 视频?

发布于 2024-11-05 18:49:34 字数 390 浏览 1 评论 0原文

如何停止在我的网络视图中播放的 YouTube 视频?当我单击后退按钮时,视频不会停止,而是在后台继续播放。

代码:

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(18

遗弃M 2024-11-12 18:49:34

请参阅以下关于 WebView 线程永不停止的帖子,

本质上是您'您需要从您自己的 Activity 的 onPause 方法调用 WebView 的 onPause 方法。

唯一的技巧是你不能直接调用 WebView 的 onPause 方法,因为它是隐藏的。因此,您需要通过反射间接调用它。以下代码应该帮助您开始设置自己的 Activity 的 onPause 方法:

@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) {
        ...
    }
}

请注意,上面的 try 块中的变量“webview”是该类的私有实例变量,并在 Activity 的 onCreate 方法中分配给该变量。

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.

恋你朝朝暮暮 2024-11-12 18:49:34

解决方案:1 -
花了很多时间后,我得到了暂停视频的结论,这是用HTML的WebView 概念来播放的。

只需在使用 WebView 的位置重写 Activity 或 Fragment 上的 onPause() 方法,然后调用它即可。这对我有用。

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

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

解决方案:2 -
如果上述解决方案不适合您,那么您可以强制 WebView 加载不存在的 html 文件。

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

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");
2024-11-12 18:49:34

您还必须实现 onResume() 方法,否则第二次将无法工作

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

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

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();
}
嗼ふ静 2024-11-12 18:49:34

在运行 Android 2.3.3 的 Samsung Galaxy S 上,上述解决方案对我来说失败了。
但我成功尝试了以下解决方法:

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

我强制 webview 加载不存在的 html 文件。这似乎迫使网络视图清理东西。

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.

不乱于心 2024-11-12 18:49:34

试试这个:

@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();
}

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();
}
来日方长 2024-11-12 18:49:34

这是我个人最喜欢的:

@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();
}

如果视图仅暂停,它会暂停 webview,但在活动完成时清除它。

这至少需要 Android 3.0 - API 11 (Honeycomb)

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)

抽个烟儿 2024-11-12 18:49:34
@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);
}

有用

@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

寄人书 2024-11-12 18:49:34

上述方法对我不起作用,对我有用的一种方法是:

@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);
}

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);
}
淑女气质 2024-11-12 18:49:34

Webview.loadUrl("关于:空白");

它也在工作

Webview.loadUrl("about:blank");

it is also working

傲性难收 2024-11-12 18:49:34

遇到这个问题后,似乎 onPause 可能没有做任何事情......对我来说,它并没有停止后台播放的任何内容。

所以我的代码现在看起来像

@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();
}

希望它可以帮助任何与我有同样问题的人

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

锦爱 2024-11-12 18:49:34

你可以尝试这个,

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

如果正在加载的页面是你可以编辑的页面,那么你可以编写一个 javascript 方法来停止音频并在你想停止时调用。

Javascript函数

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

来自Andorid调用此方法

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

如果页面不可编辑,您可以注入js代码

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

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

   }

如何注入详细信息请参见此处

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

伴我老 2024-11-12 18:49:34

基于@sommesh 的回答:

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)
    }
}

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)
    }
}
梦罢 2024-11-12 18:49:34

对我有用。

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

This works for me.

@Override
protected void onPause() {
    super.onPause();
    if (wViewCampaign != null){
        wViewCampaign.stopLoading(); 
        wViewCampaign.loadUrl("");
        wViewCampaign.reload();
        wViewCampaign = null;
    }
}
意中人 2024-11-12 18:49:34

当执行 Activity 的方法 onPause() 时,您可以使用 WebView 的方法 onPause() 来完成此操作:

@override
public void onPause() {
        super.onPause();
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
          webview.onPause();
        }
}
  • 适用于API >= 11蜂窝

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)
油焖大侠 2024-11-12 18:49:34

我尝试了以上所有答案,但大多数对我不起作用。所以我只是编写自己的解决方案,该解决方案在 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;
    }

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;
    }
吹泡泡o 2024-11-12 18:49:34

这是在尝试了此页面上提供的每个代码后最终起作用的。呃!

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

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

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();
}
在你怀里撒娇 2024-11-12 18:49:34

在我的情况下,播放器在 WebView 处于“onPause”状态后继续运行。
因此,我在播放视频或音乐之前检查 WebView 是否附加到窗口。

它是 JavaScriptInterface 方法,用于检查 WebView 的“isAttachedToWindow()”返回 true/false。

(而且我没有忘记在Activity/Fragment中调用onPause/onResume。)

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

他夏了夏天 2024-11-12 18:49:34

这段代码非常适合我。

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

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();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文