html视频没有在android webview中播放

Posted

技术标签:

【中文标题】html视频没有在android webview中播放【英文标题】:html video not playing in android webview 【发布时间】:2013-10-15 07:29:04 【问题描述】:

我正在使用 android webview,在这里我坚持使用视频。实际上,我正在尝试播放资产文件夹中的视频,但它没有播放。 在这里,我浏览了所有链接和解决方案,但没有什么对我有用-

[链接1][1] https://code.google.com/p/html5webview/source/browse/trunk/HTML5WebView/src/org/itri/html5webview/TestHTML5WebView.java

[链接2][2] http://www.mocoven.com/blog/?p=199

下面我附上代码-

//Html5webview

package com.example.jbb_video_play;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.GeolocationPermissions;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;

public class HTML5WebView extends WebView 

        private Context mContext;                                                
        private MyWebChromeClient mWebChromeClient;                                      
        private View mCustomView;                                                            
        private FrameLayout mCustomViewContainer;                                                   
        private WebChromeClient.CustomViewCallback mCustomViewCallback;

        private FrameLayout mContentView;                                                  
        private FrameLayout mBrowserFrameLayout;                                                     
        private FrameLayout mLayout;                                                    

    static final String LOGTAG = "HTML5WebView";

        @SuppressLint("NewApi")
        private void init(Context context) 
                mContext = context;            
                Activity a = (Activity) mContext;

                mLayout = new FrameLayout(context);

                mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(a).inflate(R.layout.custom_screen, null);
                mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(R.id.main_content);
                mCustomViewContainer = (FrameLayout) mBrowserFrameLayout.findViewById(R.id.fullscreen_custom_content);

                mLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);

                mWebChromeClient = new MyWebChromeClient();
            setWebChromeClient(mWebChromeClient);

            setWebViewClient(new MyWebViewClient());

            // Configure the webview
            WebSettings s = getSettings();
            s.setBuiltInZoomControls(true);
            s.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
            s.setUseWideViewPort(true);
            s.setAllowContentAccess(true);
            s.setAllowFileAccess(true);
            s.setAllowUniversalAccessFromFileURLs(true);
            s.setAllowFileAccessFromFileURLs(true);
            s.setMediaPlaybackRequiresUserGesture(true);
            s.setNeedInitialFocus(true);
            s.setSaveFormData(true);
            s.setUserAgentString(getUrl());
            s.setLoadsImagesAutomatically(true);
            s.setBlockNetworkLoads(false);
            s.setBlockNetworkImage(false);
            s.setDatabaseEnabled(true);
            s.setjavascriptCanOpenWindowsAutomatically(true);
            s.setJavaScriptEnabled(true);
            s.setSupportMultipleWindows(true);
            s.setLoadWithOverviewMode(true);
            s.setSavePassword(true);
            s.setSaveFormData(true);
            s.setJavaScriptEnabled(true);

            // enable navigator.geolocation
            s.setGeolocationEnabled(true);
           // s.setGeolocationDatabasePath("/data/data/org.itri.html5webview/databases/");

            // enable Web Storage: localStorage, sessionStorage
            s.setDomStorageEnabled(true);

            mContentView.addView(this);
        

        public HTML5WebView(Context context) 
                super(context);
                init(context);
        

        public HTML5WebView(Context context, AttributeSet attrs) 
                super(context, attrs);
                init(context);
        

        public HTML5WebView(Context context, AttributeSet attrs, int defStyle) 
                super(context, attrs, defStyle);
                init(context);
        

        public FrameLayout getLayout() 
                return mLayout;
        

    public boolean inCustomView() 
                return (mCustomView != null);
        

    public void hideCustomView() 
                mWebChromeClient.onHideCustomView();
        

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

    private class MyWebChromeClient extends WebChromeClient 
                private Bitmap          mDefaultVideoPoster;
                private View            mVideoProgressView;

        @Override
                public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback)
                
                        //Log.i(LOGTAG, "here in on ShowCustomView");
                HTML5WebView.this.setVisibility(View.GONE);

                // if a view already exists then immediately terminate the new one
                if (mCustomView != null) 
                    callback.onCustomViewHidden();
                    return;
                

                mCustomViewContainer.addView(view);
                mCustomView = view;
                mCustomViewCallback = callback;
                mCustomViewContainer.setVisibility(View.VISIBLE);
                

                @Override
                public void onHideCustomView() 

                        if (mCustomView == null)
                                return;        

                        // Hide the custom view.
                        mCustomView.setVisibility(View.GONE);

                        // Remove the custom view from its container.
                        mCustomViewContainer.removeView(mCustomView);
                        mCustomView = null;
                        mCustomViewContainer.setVisibility(View.GONE);
                        mCustomViewCallback.onCustomViewHidden();

                        HTML5WebView.this.setVisibility(View.VISIBLE);

                //Log.i(LOGTAG, "set it to webVew");
                

                @Override
                public Bitmap getDefaultVideoPoster() 
                        //Log.i(LOGTAG, "here in on getDefaultVideoPoster");    
                        if (mDefaultVideoPoster == null) 
                                mDefaultVideoPoster = BitmapFactory.decodeResource(
                                                getResources(), R.drawable.ic_launcher);
                    
                        return mDefaultVideoPoster;
                

                @Override
                public View getVideoLoadingProgressView() 
                        //Log.i(LOGTAG, "here in on getVideoLoadingPregressView");

                if (mVideoProgressView == null) 
                    LayoutInflater inflater = LayoutInflater.from(mContext);
                    mVideoProgressView = inflater.inflate(R.layout.video_loading_progress, null);
                
                return mVideoProgressView;
                

         @Override
         public void onReceivedTitle(WebView view, String title) 
            ((Activity) mContext).setTitle(title);
         

         @Override
         public void onProgressChanged(WebView view, int newProgress) 
                 ((Activity) mContext).getWindow().setFeatureInt(Window.FEATURE_PROGRESS, newProgress*100);
         

         @Override
         public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) 
             callback.invoke(origin, true, false);
         
    

        private class MyWebViewClient extends WebViewClient 
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) 
                Log.i(LOGTAG, "shouldOverrideUrlLoading: "+url);
                // don't override URL so that stuff within iframe can work properly
                // view.loadUrl(url);
                return false;
            
        

        static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
        new FrameLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

和 //MainActivity

public class MainActivity extends Activity 

    HTML5WebView mWebView;

   @Override
   public void onCreate(Bundle savedInstanceState) 
       super.onCreate(savedInstanceState);
       mWebView = new HTML5WebView(this);

       if (savedInstanceState != null) 
               mWebView.restoreState(savedInstanceState);
        else 


           try
        
        AssetManager m=this.getAssets();
        InputStream ios=    m.open("nasa.html");
        BufferedReader br=new BufferedReader(new InputStreamReader(ios));

        StringBuffer nb=new StringBuffer();
        String line="";

        while((line=br.readLine())!=null)
        
            nb.append(line);
        

        String final_data=nb.toString();

        //mWebView.loadDataWithBaseURL("file:///android_asset/", final_data, "text/html", "utf-8", null);


              // mWebView.loadUrl("http://freebsd.csie.nctu.edu.tw/~freedom/html5/");
               mWebView.loadUrl("file:///android_asset/nasa.html");

        
           catch (Exception e) 
            // TODO: handle exception
        
       
       setContentView(mWebView.getLayout());
   




    @Override
    public void onSaveInstanceState(Bundle outState) 
        super.onSaveInstanceState(outState);
        mWebView.saveState(outState);
    

    @Override
    public void onStop() 
        super.onStop();
        mWebView.stopLoading();
    

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) 
        if (keyCode == KeyEvent.KEYCODE_BACK) 
            if (mWebView.inCustomView()) 
                mWebView.hideCustomView();
                return true;
            
        
        return super.onKeyDown(keyCode, event);
    

    @Override
    public void onConfigurationChanged(Configuration newConfig) 
         super.onConfigurationChanged(newConfig);
    


//资产文件夹中的html文件

<!DOCTYPE html>
<head></head>

<body>
<video id="video"   controls="controls" >
<source src="clipcanvas_14348_offline.mp4" type="video/mp4">
</video>

</body>

<footer>
</footer>

及视频链接

http://www.clipcanvas.com/a/video-clip-downloads/

请给我任何可行的解决方案,谢谢

【问题讨论】:

你的问题解决了吗?! 【参考方案1】:

当视频在 div 中时会发生这种情况,您应该在代码中添加以下行:

    webView.getSettings().setDomStorageEnabled(true);
    webView.getSettings().setAppCacheEnabled(true);
    webView.getSettings().setAppCachePath(getApplicationContext().getFilesDir().getAbsolutePath() + "/cache");
    webView.getSettings().setDatabaseEnabled(true);
    webView.getSettings().setDatabasePath(getApplicationContext().getFilesDir().getAbsolutePath() + "/databases");

【讨论】:

这真的对你有帮助吗?因为我面临着类似的问题! 是的,它帮助了我 对我来说,只有第一行有帮助。我已经嵌入了.html 视频并且它有效。 webView.getSettings().setDomStorageEnabled(true); 这一行完成所有工作【参考方案2】:

WebViewClient 旁边,您还应该将WebChromeClient 添加到WebView

webView.setWebViewClient(new MyWebViewClient());               
webView.setWebChromeClient(new WebChromeClient());
webView.getSettings().setJavaScriptEnabled(true);              
webView.loadUrl("http://118.102.182.53:9080/swami/index.html");

对于 Android 3.x 版本,您还可以在 AndroidManifest.xml 中设置 hardwareAccelerated="true

【讨论】:

这里我要播放放在本地文件夹中的文件 添加“webView.getSettings().setMediaPlaybackRequiresUserGesture(false);”在“webView.getSettings().setJavaScriptEnabled(true);”之后让 webview 自动加载媒体 你拯救了我的一天 拯救了我的一天 ++【参考方案3】:

只需添加 android:hardwareAccelerated="true" 用于 AndroidManifest.xml 中的活动标签

【讨论】:

以上是关于html视频没有在android webview中播放的主要内容,如果未能解决你的问题,请参考以下文章

html5 视频不适用于 android webview

html5视频无法与android webview一起使用

如何使用android在webview中播放视频?

Android WebView html5 视频强制全屏

Android WebView 中的 HTML5 视频不一致

为啥 Youtube 视频没有在 webview android 中播放