仅作记录
参考链接
https://blog.csdn.net/zgx19910405/article/details/87623697
https://www.jianshu.com/p/3405ef3a4632
public class WebViewPool {
private WebViewPool() {
}
private static final int CACHED_WEBVIEW_MAX_NUM = 2;
private static final Stack<DWebView> mCachedWebViewStack = new Stack<>();
public static WebViewPool getInstance() {
return WebViewPool.Holder.INSTANCE;
}
private static class Holder {
private static final WebViewPool INSTANCE = new WebViewPool();
}
/**
* 创建WebView实例
* 用了applicationContext
*/
public void preload() {
Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
@Override
public boolean queueIdle() {
if (mCachedWebViewStack.size() < CACHED_WEBVIEW_MAX_NUM) {
mCachedWebViewStack.push(createWebView());
}
return false;
}
});
}
private DWebView createWebView() {
DWebView webview = new DWebView(new MutableContextWrapper(Utils.getApp()));
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
//设置支持DomStorage
settings.setDomStorageEnabled(true);
// 实现8倍缓存
settings.setAppCacheMaxSize(Long.MAX_VALUE);
settings.setAllowFileAccess(true);
// 开启Application Cache功能
settings.setAppCacheEnabled(true);
//取得缓存路径
String appCachePath = Utils.getApp().getCacheDir().getAbsolutePath();
//设置路径
//API 19 deprecated
settings.setDatabasePath(appCachePath);
// 设置Application caches缓存目录
settings.setAppCachePath(appCachePath);
//是否启用数据库
settings.setDatabaseEnabled(true);
settings.setBuiltInZoomControls(false);
settings.setUseWideViewPort(true);
settings.setLoadWithOverviewMode(true);
settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
//设置存储模式 建议缓存策略为,判断是否有网络,有的话,使用LOAD_DEFAULT,无网络时,使用LOAD_CACHE_ELSE_NETWORK
settings.setCacheMode(WebSettings.LOAD_DEFAULT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
settings.setAllowUniversalAccessFromFileURLs(true);
}
CookieManager cookieManager = CookieManager.getInstance();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
cookieManager.setAcceptThirdPartyCookies(webview, true);
}
return webview;
}
/**
* 从缓存池中获取合适的WebView
*
* @param context activity context
* @return WebView
*/
public DWebView getWebView(Context context) {
// 为空,直接返回新实例
if (mCachedWebViewStack == null || mCachedWebViewStack.isEmpty()) {
DWebView web = createWebView();
MutableContextWrapper contextWrapper = (MutableContextWrapper) web.getContext();
contextWrapper.setBaseContext(context);
return web;
}
DWebView webView = mCachedWebViewStack.pop();
// webView不为空,则开始使用预创建的WebView,并且替换Context
MutableContextWrapper contextWrapper = (MutableContextWrapper) webView.getContext();
contextWrapper.setBaseContext(context);
return webView;
}
}