Android WebView實現全屏播放視頻

介紹

最近項目開發中用到瞭WebView播放視頻的功能,總結瞭開發中犯過的錯誤,這些錯誤在開發是及容易遇到的,所以我這裡總結瞭一下,希望大傢看到後不要再犯類似的錯誤,盡可能提高開發效率:

這個Demo我這裡也參考瞭網上寫的一個比較好的一個Demo,經過總結修改,寫出來的。

主要代碼

以下是相應代碼:

MainActivity:

package com.androidwebviewdemo;
 
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebChromeClient.CustomViewCallback;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
 
/**
 * 使用WebView播放視頻時需要註意的地方:
 * 1、加網絡訪問權限(及其他所需要的權限); 
 * 2、WebViewClient中方法shouldOverrideUrlLoading可用來實現點擊webView頁面的鏈接;
 * 3、WebView中播放視頻需要添加webView.setWebChromeClient(new WebChromeClient());
 * 4、視頻豎屏時,點擊全屏,想要切換到橫屏全屏的狀態,那麼必須在Manifest.xml配置文件該Activity的
 * 	配置文件中添加android:configChanges="orientation|screenSize"語句。
 * 5、如果視頻不能播放,或者播放比較卡,可以采用硬件加速,即在Application,或所在的Activity的配置文件中添加
 * 	android:hardwareAccelerated="true"即可。
 * @author zhongyao
 */
public class MainActivity extends Activity {
	private WebView webView;
	private FrameLayout video_fullView;// 全屏時視頻加載view
	private View xCustomView;
	private ProgressDialog waitdialog = null;
	private CustomViewCallback xCustomViewCallback;
	private myWebChromeClient xwebchromeclient;
 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉應用標題
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.activity_main);
		
		waitdialog = new ProgressDialog(this);
		waitdialog.setTitle("提示");
		waitdialog.setMessage("視頻頁面加載中...");
		waitdialog.setIndeterminate(true);
		waitdialog.setCancelable(true);
		waitdialog.show();
 
		webView = (WebView) findViewById(R.id.webView);
		video_fullView = (FrameLayout) findViewById(R.id.video_fullView);
 
		WebSettings ws = webView.getSettings();
		ws.setBuiltInZoomControls(true);// 隱藏縮放按鈕
		// ws.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);// 排版適應屏幕
 
		ws.setUseWideViewPort(true);// 可任意比例縮放
		ws.setLoadWithOverviewMode(true);// setUseWideViewPort方法設置webview推薦使用的窗口。setLoadWithOverviewMode方法是設置webview加載的頁面的模式。
 
		ws.setSavePassword(true);
		ws.setSaveFormData(true);// 保存表單數據
		ws.setJavaScriptEnabled(true);
		ws.setGeolocationEnabled(true);// 啟用地理定位
		ws.setGeolocationDatabasePath("/data/data/org.itri.html5webview/databases/");// 設置定位的數據庫路徑
		ws.setDomStorageEnabled(true);
		ws.setSupportMultipleWindows(true);// 新加
		xwebchromeclient = new myWebChromeClient();
		webView.setWebChromeClient(xwebchromeclient);
		webView.setWebViewClient(new myWebViewClient());
		webView.loadUrl("http://look.appjx.cn/mobile_api.php?mod=news&id=12604");
	}
 
	public class myWebViewClient extends WebViewClient {
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			view.loadUrl(url);
			return false;
		}
 
		@Override
		public void onPageFinished(WebView view, String url) {
			super.onPageFinished(view, url);
			waitdialog.dismiss();
		}
	}
 
	public class myWebChromeClient extends WebChromeClient {
		private View xprogressvideo;
 
		// 播放網絡視頻時全屏會被調用的方法
		@Override
		public void onShowCustomView(View view, CustomViewCallback callback) {
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
			webView.setVisibility(View.INVISIBLE);
			// 如果一個視圖已經存在,那麼立刻終止並新建一個
			if (xCustomView != null) {
				callback.onCustomViewHidden();
				return;
			}
			video_fullView.addView(view);
			xCustomView = view;
			xCustomViewCallback = callback;
			video_fullView.setVisibility(View.VISIBLE);
		}
 
		// 視頻播放退出全屏會被調用的
		@Override
		public void onHideCustomView() {
			if (xCustomView == null)// 不是全屏播放狀態
				return;
 
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
			xCustomView.setVisibility(View.GONE);
			video_fullView.removeView(xCustomView);
			xCustomView = null;
			video_fullView.setVisibility(View.GONE);
			xCustomViewCallback.onCustomViewHidden();
			webView.setVisibility(View.VISIBLE);
		}
 
		// 視頻加載時進程loading
		@Override
		public View getVideoLoadingProgressView() {
			if (xprogressvideo == null) {
				LayoutInflater inflater = LayoutInflater
						.from(MainActivity.this);
				xprogressvideo = inflater.inflate(
						R.layout.video_loading_progress, null);
			}
			return xprogressvideo;
		}
	}
 
	/**
	 * 判斷是否是全屏
	 * 
	 * @return
	 */
	public boolean inCustomView() {
		return (xCustomView != null);
	}
 
	/**
	 * 全屏時按返加鍵執行退出全屏方法
	 */
	public void hideCustomView() {
		xwebchromeclient.onHideCustomView();
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
	}
 
	@Override
	protected void onResume() {
		super.onResume();
		super.onResume();
		webView.onResume();
		webView.resumeTimers();
 
		/**
		 * 設置為橫屏
		 */
		if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		}
	}
 
	@Override
	protected void onPause() {
		super.onPause();
		webView.onPause();
		webView.pauseTimers();
	}
 
	@Override
	protected void onDestroy() {
		super.onDestroy();
		super.onDestroy();
		video_fullView.removeAllViews();
		webView.loadUrl("about:blank");
		webView.stopLoading();
		webView.setWebChromeClient(null);
		webView.setWebViewClient(null);
		webView.destroy();
		webView = null;
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (inCustomView()) {
				// webViewDetails.loadUrl("about:blank");
				hideCustomView();
				return true;
			} else {
				webView.loadUrl("about:blank");
				MainActivity.this.finish();
			}
		}
		return false;
	}
}

activity_main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
 
    <FrameLayout
        android:id="@+id/video_fullView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:visibility="gone" >
    </FrameLayout>
 
    <WebView
        android:id="@+id/webView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20sp" />
 
</LinearLayout>

video_loading_progress.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/progress_indicator"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:orientation="vertical" >
 
    <ProgressBar
        android:id="@android:id/progress"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center" />
 
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:paddingTop="5dip"
        android:text="正在玩命加載視頻中。。。"
        android:textColor="?android:attr/textColorPrimary"
        android:textSize="14sp" />
 
</LinearLayout>

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidwebviewdemo"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
 
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_GPS" />
    <uses-permission android:name="android.permission.ACCESS_ASSISTED_GPS" />
    <uses-permission android:name="android.permission.ACCESS_LOCATION" />
	<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
    <application
        android:allowBackup="true"
        android:hardwareAccelerated="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
 
        <!-- android:configChanges="orientation|keyboardHidden" -->
        <!-- 默認豎屏,點擊全屏後再橫屏,
         	那麼activity必須配置android:configChanges="orientation|screenSize"
			這樣一來,旋轉屏幕,隻會調用onConfigurationChanged,不會創建新activity。
			不然的話,代碼中設置橫屏的時候,都會新建一個Activity,
			那樣就沒辦法實現點擊就橫屏全屏瞭。 -->
        <activity
            android:name="com.androidwebviewdemo.MainActivity"
            android:configChanges="orientation|screenSize"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
 
</manifest>

以上就是Android WebView實現全屏播放視頻的詳細內容,更多關於Android WebView播放視頻的資料請關註WalkonNet其它相關文章!

推薦閱讀: