Android WebView在用户按回后未停止

ua4mk5z4  于 2023-04-18  发布在  Android
关注(0)|答案(8)|浏览(133)

我正在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");
    }    
}

有什么想法可能会阻止音频播放,什么可能会导致它?谢谢!

hgncfbus

hgncfbus1#

试试这个,希望有帮助:

@Override
public void onPause() {
    myWebView.onPause();
    myWebView.pauseTimers();//this may cause adMob to stop working
    super.onPause();
}

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

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

jei2mxaa2#

您应该拨打:

webView.loadUrl("about:blank");

它将销毁所有音频/视频以及Javasript对象,并停止Webview上所有正在运行的函数

ctehm74n

ctehm74n3#

引用自https://stackoverflow.com/a/17690221/3032209
您应该分别从Activity的onPause()和onResume()调用WebView的onPause()和onResume()。
暂停与此WebView及其关联DOM、插件、JavaScript等关联的任何额外处理。例如,如果此WebView被移出屏幕,则可以调用此函数以减少不必要的CPU或网络流量。当此WebView再次处于“活动”状态时,调用onResume()。

rwqw0loc

rwqw0loc4#

在一些或所有设备中没有什么对我有效。我想这是确切的解决方案。对我很有效。
How to stop youtube video playing in Android webview?
或者对于API〉= 11,可以使用_webview.onPause();在Activity的/片段的onPause上

public void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        _webview.onPause();
}
piwo6bdm

piwo6bdm5#

在Activity的onDestroy()中执行以下操作:

@Override
protected void onDestroy() {
    super.onDestroy();
    webView.destroy();
}
wkyowqbh

wkyowqbh6#

您可以使用Activity的方法onPause()来实现:

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

添加用于API〉= 11(Honeycomb)的验证

dpiehjr4

dpiehjr47#

private void destroyWebView() {
        if (webView != null) {
            webView.clearHistory();
            webView.clearCache(false);
            webView.loadUrl("about:blank");
            webView.onPause();
            webView.removeAllViews();
            // webView.destroyDrawingCache();

            // NOTE: This pauses JavaScript execution for ALL WebViews,
            // do not use if you have other WebViews still alive.
            // If you create another WebView after calling this,
            // make sure to call mWebView.resumeTimers().
            // webView.pauseTimers();//adMob will fail to load if called
            webView.destroy();
            webView = null;
        }
    }
6ie5vjzr

6ie5vjzr8#

我做的方法是通过调用webview对象的clearFocus。在我的例子中,我有堆叠的片段。所以对于不在顶部的片段,我调用了webview示例的clearFocus。它为我暂停视频。

相关问题