参考链接:https://blog.csdn.net/zgx19910405/article/details/87623697
第一步:
创建工具类来实现WebView的实例化和资源释放
public class WebViewPools {
//AtomicReference提供了以无锁方式访问共享资源的能力
private static WebViewPools mWebPools = null;
/**
* 引用类型的原子类
**/
private static final AtomicReference<WebViewPools> mAtomicReference = new AtomicReference<>();
private final Queue<WebView> mWebViews;
private Object lock = new Object();
private WebViewPools() {
mWebViews = new LinkedBlockingQueue<>();
}
public static WebViewPools getInstance() {
for (; ; ) {
if (mWebPools != null)
return mWebPools;
if (mAtomicReference.compareAndSet(null, new WebViewPools()))
return mWebPools = mAtomicReference.get();
}
}
/**
* 页面销毁
* (1)去除WebView的上下文,避免内存泄漏
* (2)加入缓存
**/
public void recycle(WebView webView) {
recycleInternal(webView);
}
/**
* 页面加入浏览器
* (1)缓存没有,则新建webView
**/
public WebView acquireWebView(Activity activity) {
return acquireWebViewInternal(activity);
}
private WebView acquireWebViewInternal(Activity activity) {
WebView mWebView = mWebViews.poll();
if (mWebView == null) {
synchronized (lock) {
return new WebView(new MutableContextWrapper(activity));
}
} else {
MutableContextWrapper mMutableContextWrapper = (MutableContextWrapper) mWebView.getContext();
mMutableContextWrapper.setBaseContext(activity);
return mWebView;
}
}
private void recycleInternal(WebView webView) {
try {
if (webView.getContext() instanceof MutableContextWrapper) {
MutableContextWrapper mContext = (MutableContextWrapper) webView.getContext();
mContext.setBaseContext(mContext.getApplicationContext());
mWebViews.offer(webView);
}
if (webView.getContext() instanceof Activity) {
throw new RuntimeException("leaked");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
第二步:
在Application或者主页预先加载一个WebView并释放资源
//long l = System.currentTimeMillis();
WebView webView = WebViewPools.getInstance().acquireWebView(this);
//LogUtil.logD("第一次初始化:" + (System.currentTimeMillis() - l));
WebViewPools.getInstance().recycle(webView);
第三步:
在需要使用的地方通过WebViewPools取出WebView进行使用
LinearLayout ll_webview = findViewById(R.id.ll_webview);
WebView x5Webview = WebViewPools.getInstance().acquireWebView(this);
ll_webview.addView(x5Webview, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
第四步:
页面销毁时记得释放资源
@Override
protected void onDestroy() {
super.onDestroy();
ll_webview.removeAllViews();
WebViewPools.getInstance().recycle(x5Webview);
}
网友评论