定义自己的MyWebview继承WebView,本类中对webview进行基本的设置
package widget;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ZoomButtonsController;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/*******************************************************************************
* * 描述 :widget
* * Create Date :16/5/3 17:54
* * Version :1.0.0
* *
* * Modified Date Modified By Why
* * xxxx-xx-xx xxx xxxxx
* * ... ...
********************************************************************************/
public class MyWebView extends WebView {
private Context mContext;
private int mProgress = 100;
private boolean mIsLoading = false;
private String mLoadedUrl;
private static boolean mBoMethodsLoaded = false;
private static Method mOnPauseMethod = null;
private static Method mOnResumeMethod = null;
private static Method mSetFindIsUp = null;
private static Method mNotifyFindDialogDismissed = null;
public MyWebView(Context context) {
super(context);
this.mContext = context;
this.initializeOptions();
this.loadMethods();
}
public MyWebView(Context context, AttributeSet attrs) {
super(context, attrs);
this.mContext = context;
this.initializeOptions();
this.loadMethods();
}
@SuppressLint({"NewApi"})
public void initializeOptions() {
WebSettings settings = this.getSettings();
settings.setJavaScriptEnabled(true);
settings.setLoadsImagesAutomatically(true);
settings.setUseWideViewPort(true);
settings.setLoadWithOverviewMode(true);
settings.setSaveFormData(true);
settings.setSavePassword(true);
settings.setDefaultZoom(WebSettings.ZoomDensity.MEDIUM);
if(Build.VERSION.SDK_INT >= 8) {
settings.setPluginState(WebSettings.PluginState.ON);
}
settings.setSupportZoom(true);
if(Build.VERSION.SDK_INT >= 11) {
settings.setBuiltInZoomControls(true);
settings.setDisplayZoomControls(false);
} else {
this.getControlls();
}
settings.setSupportMultipleWindows(true);
this.setLongClickable(true);
this.setScrollbarFadingEnabled(true);
//this.setScrollBarStyle(0);
this.setDrawingCacheEnabled(true);
settings.setAppCacheEnabled(true);
settings.setDatabaseEnabled(true);
settings.setDomStorageEnabled(true);
}
private void getControlls() {
try {
Class e = Class.forName("android.webkit.WebView");
Method method = e.getMethod("getZoomButtonsController", new Class[0]);
ZoomButtonsController var3 = (ZoomButtonsController)method.invoke(this, new Object[]{Boolean.valueOf(true)});
} catch (Exception var4) {
var4.printStackTrace();
}
}
public boolean onTouchEvent(MotionEvent ev) {
int action = ev.getAction();
if(action != 0 && action != 5 && action != 5 && action != 261 && action != 517) {
if(action == 1 || action == 6 || action == 6 || action == 262 || action == 518) {
this.getSettings().setBuiltInZoomControls(false);
this.getSettings().setSupportZoom(false);
}
} else if(ev.getPointerCount() > 1) {
this.getSettings().setBuiltInZoomControls(true);
this.getSettings().setSupportZoom(true);
} else {
this.getSettings().setBuiltInZoomControls(false);
this.getSettings().setSupportZoom(false);
}
return super.onTouchEvent(ev);
}
public void loadUrl(String url) {
this.mLoadedUrl = url;
super.loadUrl(url);
}
public void loadAdSweep() {
}
public void setProgress(int progress) {
this.mProgress = progress;
}
public int getProgress() {
return this.mProgress;
}
public void notifyPageStarted() {
this.mIsLoading = true;
}
public void notifyPageFinished() {
this.mProgress = 100;
this.mIsLoading = false;
}
public boolean isLoading() {
return this.mIsLoading;
}
public String getLoadedUrl() {
return this.mLoadedUrl;
}
public void resetLoadedUrl() {
this.mLoadedUrl = null;
}
public boolean isSameUrl(String url) {
return url != null?url.equalsIgnoreCase(this.getUrl()):false;
}
public void doOnPause() {
if(mOnPauseMethod != null) {
try {
mOnPauseMethod.invoke(this, new Object[0]);
} catch (IllegalArgumentException var2) {
Log.e("CustomWebView", "doOnPause(): " + var2.getMessage());
} catch (IllegalAccessException var3) {
Log.e("CustomWebView", "doOnPause(): " + var3.getMessage());
} catch (InvocationTargetException var4) {
Log.e("CustomWebView", "doOnPause(): " + var4.getMessage());
}
}
}
public void doOnResume() {
if(mOnResumeMethod != null) {
try {
mOnResumeMethod.invoke(this, new Object[0]);
} catch (IllegalArgumentException var2) {
Log.e("CustomWebView", "doOnResume(): " + var2.getMessage());
} catch (IllegalAccessException var3) {
Log.e("CustomWebView", "doOnResume(): " + var3.getMessage());
} catch (InvocationTargetException var4) {
Log.e("CustomWebView", "doOnResume(): " + var4.getMessage());
}
}
}
public void doSetFindIsUp(boolean value) {
if(mSetFindIsUp != null) {
try {
mSetFindIsUp.invoke(this, new Object[]{Boolean.valueOf(value)});
} catch (IllegalArgumentException var3) {
Log.e("CustomWebView", "doSetFindIsUp(): " + var3.getMessage());
} catch (IllegalAccessException var4) {
Log.e("CustomWebView", "doSetFindIsUp(): " + var4.getMessage());
} catch (InvocationTargetException var5) {
Log.e("CustomWebView", "doSetFindIsUp(): " + var5.getMessage());
}
}
}
public void doNotifyFindDialogDismissed() {
if(mNotifyFindDialogDismissed != null) {
try {
mNotifyFindDialogDismissed.invoke(this, new Object[0]);
} catch (IllegalArgumentException var2) {
Log.e("CustomWebView", "doNotifyFindDialogDismissed(): " + var2.getMessage());
} catch (IllegalAccessException var3) {
Log.e("CustomWebView", "doNotifyFindDialogDismissed(): " + var3.getMessage());
} catch (InvocationTargetException var4) {
Log.e("CustomWebView", "doNotifyFindDialogDismissed(): " + var4.getMessage());
}
}
}
private void loadMethods() {
if(!mBoMethodsLoaded) {
try {
mOnPauseMethod = WebView.class.getMethod("onPause", new Class[0]);
mOnResumeMethod = WebView.class.getMethod("onResume", new Class[0]);
} catch (SecurityException var4) {
Log.e("CustomWebView", "loadMethods(): " + var4.getMessage());
mOnPauseMethod = null;
mOnResumeMethod = null;
} catch (NoSuchMethodException var5) {
Log.e("CustomWebView", "loadMethods(): " + var5.getMessage());
mOnPauseMethod = null;
mOnResumeMethod = null;
}
try {
mSetFindIsUp = WebView.class.getMethod("setFindIsUp", new Class[]{Boolean.TYPE});
mNotifyFindDialogDismissed = WebView.class.getMethod("notifyFindDialogDismissed", new Class[0]);
} catch (SecurityException var2) {
Log.e("CustomWebView", "loadMethods(): " + var2.getMessage());
mSetFindIsUp = null;
mNotifyFindDialogDismissed = null;
} catch (NoSuchMethodException var3) {
Log.e("CustomWebView", "loadMethods(): " + var3.getMessage());
mSetFindIsUp = null;
mNotifyFindDialogDismissed = null;
}
mBoMethodsLoaded = true;
}
}
}
在WebViewActivity布局中直接引用MyWebView,使用:
package module.web;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.ValueCallback;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;
import cn.igap.sale.R;
import common.BaseActivity;
import common.ServerConfig;
import common.UserConfig;
import view.LoadingView;
import widget.MyWebView;
public class WebViewActivity extends BaseActivity {
private Context context;
private MyWebView webView;
private String url;
private String title;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
context = this;
url = getIntent().getStringExtra("url");
title = getIntent().getStringExtra("title");
initView();
}
@SuppressLint("NewApi")
private void initView() {
if (!TextUtils.isEmpty(title)) {
((TextView) findViewById(R.id.title)).setText(title);
}
findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
webView = (MyWebView) findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
webSettings.setAppCacheEnabled(true);
webSettings.setDatabaseEnabled(true);
webSettings.setDomStorageEnabled(true);//开启DOM缓存,关闭的话H5自身的一些操作是无效的
webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowFileAccess(true);
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
}
webSettings.setBlockNetworkImage(false);
CookieSyncManager.createInstance(this);
final CookieManager cookieManager = CookieManager.getInstance();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
cookieManager.setAcceptThirdPartyCookies(webView, true);
}
cookieManager.setAcceptCookie(true);
cookieManager.removeSessionCookie();
cookieManager.setCookie(url, "ticket=" + UserConfig.getTicket());
if (Build.VERSION.SDK_INT < 21) {
CookieSyncManager.getInstance().sync();
} else {
CookieManager.getInstance().flush();
}
if (url != null) {
webView.loadUrl(url);
} else {
toast("数据出错");
}
//覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为,使网页用WebView打开
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
//返回值是true的时候控制去WebView打开,为false调用系统浏览器或第三方浏览器
if (url.contains("http://backtoapp/?BackToApp")) {
finish();
} else {
view.loadUrl(url);
}
return true;
}
});
}
long exitTime = 0;
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
webView.goBack();
return true;
} else {
if (System.currentTimeMillis() - exitTime > 2500) {
toast("再按一次退出网页");
exitTime = System.currentTimeMillis();
} else {
finish();
}
return true;
}
}
/**
* 结束时销毁webview,避免内存消耗
*/
@Override
protected void onDestroy() {
if (webView != null) {
webView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);//加载空地址
webView.clearCache(true);
webView.clearHistory();
((ViewGroup) webView.getParent()).removeView(webView);
webView.destroy();
webView = null;
}
super.onDestroy();
}
}