35

我正在 WebView 中播放 YouTube 视频。我可以播放它,但是当人离开屏幕时,我无法停止播放音频。

我在 onDestroy 和 onPause 中尝试了各种方法,或者将它们完全取出,但它们似乎并没有什么不同。

有谁知道为什么即使在应用程序关闭并且用户打开其他应用程序后音频仍然播放并且不会停止?

这是我全班的代码:

import com.flurry.android.FlurryAgent;

import utils.SendEmail;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebSettings.PluginState;
import android.widget.Button;

public class YoutubeActivity extends Activity
{
    WebView webview = null;

    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        webview = new WebView(this);

            setContentView(webview);

            webview.getSettings().setAppCacheEnabled(false);
            webview.getSettings().setJavaScriptEnabled(true);
            webview.setInitialScale(1);
            webview.getSettings().setPluginState(PluginState.ON);

            WebSettings webSettings = webview.getSettings();

            webSettings.setLoadsImagesAutomatically(true);
            webSettings.setLoadWithOverviewMode(true);
            webSettings.setBuiltInZoomControls(true);        
            webSettings.setUseWideViewPort(true);

            webview.setWebViewClient(new WebViewClient() {
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    view.loadUrl(url);              
                    return false;
                }
            });        


            webview.setWebChromeClient(new WebChromeClient(){});

            webSettings.setDomStorageEnabled(true);
            webSettings.setAppCacheEnabled(true);
                        webSettings.setAppCachePath(getApplicationContext().getFilesDir().getAbsolutePath() + "/cache");            

            webSettings.setDatabaseEnabled(true);
            webSettings.setDatabasePath(getApplicationContext().getFilesDir().getAbsolutePath() + "/databases");

            SharedPreferences prefs = 
                    PreferenceManager.getDefaultSharedPreferences( YoutubeActivity.this);
            String url_to_watch = prefs.getString( "url_to_watch" , null ); 


            webview.loadUrl(url_to_watch);
    }



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

       try
       {
           if ( webview != null )
           {
               webview.clearCache(true); 
               webview.getSettings().setAppCacheEnabled(false);
               webview.stopLoading();
               webview.destroy();           
               sendEmail ("in pause " , "");
               webview = new WebView(this);
           }

           this.finish();
       }
       catch ( Exception e )
       {

       }
    }


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

       try
       {
           if ( webview != null )
           {
               webview = new WebView(this); // To try to reset the webview - didn't work.
           }
       }
       catch ( Exception e )
       {

       }    
    }

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

       FlurryAgent.onEndSession(this);

       try
       {
           if ( webview != null )
           {
               webview.clearView();
               webview.getSettings().setAppCacheEnabled(false);
               webview.stopLoading();
               webview.destroy();

               sendEmail ("in stop " , "");
           }
       }
       catch ( Exception e )
       {

       }

       this.finish();
    }   

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

        try
        {
            webview.onResume();
        }
        catch ( Exception  e )
        {

        }
    }

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


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) 
    {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) 
        {
            webview.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }   

    // Subject , body
    public void sendEmail( String subject , String body )
    {
        String[] params = new String[] { "http://www.problemio.com/problems/send_email_mobile.php", subject, body };

        SendEmail task = new SendEmail();
        task.execute(params);               
    }  


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

    public void onBackPressed ( )
    {   
        final AlertDialog.Builder linkedin_builder = new AlertDialog.Builder(this);

             linkedin_builder.setMessage("" +
                    "Go back to the home screen?")
                .setCancelable(false)            
                .setNegativeButton("YES", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) 
                    {
                        if ( webview != null )
                        {
                            webview.destroy();
                        }

                        Intent myIntent = new Intent(YoutubeActivity.this, MainActivity.class);
                        YoutubeActivity.this.startActivity(myIntent);
                    }
                })              
                .setPositiveButton("NO", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) 
                    {
                        dialog.cancel();                  
                    }
                })
;
         AlertDialog alert = linkedin_builder.create();
         alert.show();      
    }


    @Override
    protected void onStart()
    {
        super.onStart();
        FlurryAgent.onStartSession(this, "4VYNFK3V6RCZ53CZ3J32");
    }    
}

关于什么可能会阻止音频播放以及可能导致它的任何想法?谢谢!

4

6 回答 6

59

试试这个,希望它有帮助:

@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();
}
于 2016-05-20T04:20:34.553 回答
30

您应该致电:

webView.loadUrl("about:blank");

它将销毁所有音频/视频以及 Javasript 对象并停止 webview 上所有正在运行的功能

于 2013-11-29T01:22:50.383 回答
11

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

于 2014-05-05T08:18:21.457 回答
10

在某些或所有设备中,没有什么对我有用。这是我猜的确切解决方案。为我工作得很好。

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

或者,对于 API >= 11,您可以使用 _webview.onPause(); 在活动/片段的 onPause 上

public void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        _webview.onPause();
}
于 2014-03-11T05:54:54.493 回答
5

在活动中onDestroy()做:

@Override
protected void onDestroy() {
    super.onDestroy();
    webView.destroy();
}
于 2015-06-29T06:05:13.137 回答
3

你可以使用你的方法来做到这onPause()一点Activity

@override
public void onPause() {
    super.onPause();
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        webview.onPause();
    }
}

添加验证以在 API >= 11 (Honeycomb) 中使用

于 2015-06-23T22:40:11.147 回答