參考鏈接:https://blog.csdn.net/zgx19910405/article/details/87623697
第一步:
創(chuàng)建工具類來實現(xiàn)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);
}