IT Share you

Android WebView에서 YouTube 동영상 재생을 중지하는 방법은 무엇입니까?

shareyou 2020. 11. 25. 21:40
반응형

Android WebView에서 YouTube 동영상 재생을 중지하는 방법은 무엇입니까?


내 웹뷰에서 재생되는 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");

WebView 스레드가 멈추지 않는 다음 게시물을 참조하십시오.

기본적으로 자신의 Activity의 onPause 메서드에서 WebView의 onPause 메서드를 호출해야합니다.

이것의 유일한 트릭은 WebView의 onPause 메서드가 숨겨져 있기 때문에 직접 호출 할 수 없다는 것입니다. 따라서 리플렉션을 통해 간접적으로 호출해야합니다. 다음 코드는 활동의 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 메서드에 할당됩니다.


솔루션 : 1- 많은 시간을 보낸 후 HTML의 WebView 개념으로 재생 되는 비디오일시 중지하는 결론을 얻었습니다 <iframe>.

onPause()사용한 곳마다 Activity 또는 Fragment 메서드를 재정의 WebView하고 호출하십시오. 그것은 나를 위해 작동합니다.

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

또한 onResume () 메서드를 구현해야합니다. 그렇지 않으면 두 번째로 작동하지 않습니다.

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

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

위의 솔루션은 Android 2.3.3이 설치된 Samsung Galaxy S에서 실패했습니다. 그러나 아래 해결 방법을 시도하여 성공했습니다.

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

웹뷰가 존재하지 않는 html 파일을로드하도록 강제하고 있습니다. 이것은 webview가 일을 정리하도록 강요하는 것 같습니다.


이 시도:

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

그리고 여기 제가 개인적으로 좋아하는 것이 있습니다.

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

보기가 일시 중지 된 경우에만 웹보기를 일시 중지하지만 활동이 완료되면이를 지 웁니다.

최소 Android 3.0-API 11 (Honeycomb)이 필요합니다.


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

효과가있다


Webview.loadUrl ( "about : blank");

그것은 또한 작동합니다


이 문제가 발생한 후 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();
}

나와 같은 문제를 가진 사람에게 도움이되기를 바랍니다.


당신은 이것을 시도 할 수 있습니다

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

로드중인 페이지가 편집 할 수있는 경우 오디오를 중지하고 중지하고 싶을 때 호출하는 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"); 

   }

주입 방법 자세히보기


이것은 나를 위해 작동합니다.

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

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)

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

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

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

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


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

참고URL : https://stackoverflow.com/questions/5946698/how-to-stop-youtube-video-playing-in-android-webview

반응형