1. 程式人生 > >WebView 實現網路視訊播放

WebView 實現網路視訊播放

直接奉獻整合的程式碼,可以實現網路視訊播放
/**
*@time 2017-4-25
* @des 視訊播放 頁面
*
* **/
public class VideoPlayActivity extends Activity {

private WebView webView;
private WebSettings webSettings;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    CommonUtils.setScreenFullAndLight(this);
    //開啟硬體加速
    getWindow().setFlags( WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED, WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
    setContentView(R.layout.activity_video_play);
    initWidget();

}

private void initWidget() {

    webView =(WebView)findViewById(R.id.webView);
    webSettings   =webView.getSettings();
    // 設定WebView屬性,能夠執行Javascript指令碼
    webSettings.setJavaScriptEnabled(true);
    // 設定載入進來的頁面自適應手機螢幕
    webSettings.setLoadWithOverviewMode(true);
    webSettings.setUseWideViewPort(true);
    //設定是否可以縮放
    webView.getSettings().setBuiltInZoomControls(true);
    webSettings.setPluginState(WebSettings.PluginState.ON);

// webSettings.setPluginsEnabled(true);//可以使用外掛
webView.setNetworkAvailable(true);
// 開啟快取
webSettings.setAppCacheEnabled(true);// 應用可以有快取
webSettings.setDomStorageEnabled(true);// 設定可以使用localStorage
webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);// 優先使用快取
webSettings.setAppCacheMaxSize(10 * 1024 * 1024);// 快取最多可以有10M
//
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setAllowFileAccess(true);
webSettings.setDefaultTextEncodingName(“UTF-8”);

    webView.setVisibility(View.VISIBLE);

// webView.loadUrl(loadUrl);

    webView.setWebViewClient(new WebViewClient() {
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    });
    /**
     * 顯示自定義檢視,無此方法視訊不能播放
     */
    webView.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            super.onShowCustomView(view, callback);
        }
    });
   /* webSettings.setUserAgentString(
                    "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_4; zh-tw) AppleWebKit/533.16 (KHTML, like Gecko) Version/5.0 Safari/533.16");

*/
webView.loadUrl(loadUrl);

}

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

@Override
protected void onResume() {
    if (webView != null)
        webView.onResume();
    super.onResume();
}

@Override
protected void onDestroy() {

    super.onDestroy();
}

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

}

附帶 xml 佈局