本次记录一个关于用H5开发的webAPP 在Android客户端使用webview加载的问题,由于webapp使用localStorage存储了大量的表单信息,导致使用频繁的用户在该目录下存储的数据越来越多直到上限,localStorage的容量上限是5M,达到上限后H5程序就崩溃了,显示白屏,这问题又不容易复现,大多数用户达不到上限,使用是没问题的,出问题的手机又不在身边,经过一天的排查,查看前端代码和Android代码,最后终于锁定了是localStorage使用不当导致的。
为了以后不再被坑,在我们项目的封装的webview的类里边加了清理localStorage缓存数据的方法 WebStorage.getInstance().deleteAllData();这个方法可以加在打开网页之前,也可以加在网页关闭的时候。当然清理数据的方式有很多,也可以使用如下方式:
CookieSyncManager.createInstance(getApplicationContext());
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.removeSessionCookie();
cookieManager.removeAllCookie();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
cookieManager.removeSessionCookies(null);
cookieManager.removeAllCookie();
cookieManager.flush();
} else {
cookieManager.removeAllCookie();
CookieSyncManager.getInstance().sync();
}
deleteFile(new File(getCacheDir().getParentFile().getAbsolutePath(),"app_webview"));
public void deleteFile(File file) {
if (file.exists()) {
if (file.isFile()) {
file.delete();
} else if (file.isDirectory()) {
File files[] = file.listFiles();
for (File value : files) {
deleteFile(value);
}
}
// Timber.d("deleteFile delete file path=" + file.getAbsolutePath()+","+file.delete());
new SecurityManager().checkDelete(file.getAbsolutePath());
Timber.d("deleteFile delete file path=" + file.getAbsolutePath());
} else {
Timber.d("deleteFile delete file no exists " + file.getAbsolutePath());
}
}
文章里有不合理的地方欢迎批评指正,欢迎评论区留言交流。
关注我获取更多知识或者投稿