有一个 WebViewPool ,当“活动/片段”被删除时,将重置Webview并将其添加到WebViewPool。
以下是WebViewPool的代码:
public class WebViewPool {
private static volatile WebViewPool sINSTANCE;
private int mMaxSize;
private List<WebView> mAvailableList;
private List<WebView> mInUsedList;
private IWebViewPoolFactory mFactory;
private WebViewPool() {
}
public static WebViewPool getInstance() {
if (sINSTANCE == null) {
synchronized (WebViewPool.class) {
if (sINSTANCE == null) {
sINSTANCE = new WebViewPool();
}
}
}
return sINSTANCE;
}
public void init(IWebViewPoolFactory factory,boolean lazy) {
init(2, factory,lazy);
}
public void init(int maxSize, IWebViewPoolFactory factory,boolean lazy) {
mMaxSize = maxSize;
mFactory = factory;
mAvailableList = new ArrayList<>(maxSize);
mInUsedList = new ArrayList<>(maxSize);
if (!lazy) {
create();
}
}
private synchronized void create() {
if (mFactory == null) {
return;
}
for (int i = 0; i < mMaxSize; i++) {
WebView webView = mFactory.create(new MutableContextWrapper(APP.getApplicationContext()));
mAvailableList.add(webView);
}
}
/**
* get webview form pool
* @param context
* @return
*/
public synchronized WebView getWebView(Context context) {
if(!(context instanceof Activity)){
throw new IllegalStateException("Context must be Activity");
}
WebView webView = null;
if (mAvailableList.size() > 0) {
webView = mAvailableList.remove(0);
} else {
if (mFactory != null) {
webView = mFactory.create(new MutableContextWrapper(APP.getApplicationContext()));
}
}
if (webView != null) {
((MutableContextWrapper) webView.getContext()).setBaseContext(context);
mInUsedList.add(webView);
}
return webView;
}
/**
* reset/destroy webview when activity/fragemnt is destroyed
* @param webView
*/
public synchronized void restWebView(WebView webView) {
if (webView == null || mFactory == null) {
return;
}
mFactory.reset(webView);
((MutableContextWrapper) webView.getContext()).setBaseContext(APP.getApplicationContext());
if (mInUsedList.contains(webView)) {
mInUsedList.remove(webView);
if (mAvailableList.size() < mMaxSize) {
mAvailableList.add(webView);
} else {
mFactory.destroy(webView);
}
} else {
mFactory.destroy(webView);
}
}
}
以下是reset
函数的一些代码:
public void reset(WebView webView) {
if(webView==null){
return;
}
ViewParent viewParent = webView.getParent();
if (viewParent!=null) {
((ViewGroup)viewParent).removeView(webView);
}
webView.stopLoading();
webView.clearCache(false);
webView.loadUrl("about:blank");
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
@Override
public void run() {
webView.clearHistory();
}
}, 1000);
}
但是当重用webview时,最后的html页面有时会在新的url之前首先显示。我在Google中搜索过,但没有用。有人知道原因吗?谢谢!
答案 0 :(得分:0)
这个问题终于解决了!原因是在未加载about:blank
的情况下将重置的WebView添加到可用列表中,因此clearHistory()
不起作用。
因此,请重置Web视图,但在活动/片段被破坏时不要将其添加到可用列表,请在URL为clearHistory()
时在onPageFinished()
调用about:blank
:
@Override
public void onPageFinish(String url, boolean success) {
if("about:blank".equals(url)){
webView.clearHistory();
//then add the webview to available list;
}
}