내 활동 중 하나에 WebView가 있고 웹 페이지를로드 할 때 페이지가 Facebook에서 배경 데이터를 수집합니다.
그래도 내가 보는 것은 응용 프로그램에 표시된 페이지가 앱을 열고 새로 고칠 때마다 동일하다는 것입니다.
캐시를 사용하지 않고 WebView의 캐시 및 기록을 지우도록 WebView를 설정하려고 시도했습니다.
또한 여기 제안을 따랐습니다. WebView의 캐시를 비우는 방법?
그러나이 중 어느 것도 작동하지 않습니다.이 문제는 내 응용 프로그램의 중요한 부분이기 때문에이 문제를 극복 할 수 있다는 생각이있는 사람은 없습니다.
mWebView.setWebChromeClient(new WebChromeClient()
{
public void onProgressChanged(WebView view, int progress)
{
if(progress >= 100)
{
mProgressBar.setVisibility(ProgressBar.INVISIBLE);
}
else
{
mProgressBar.setVisibility(ProgressBar.VISIBLE);
}
}
});
mWebView.setWebViewClient(new SignInFBWebViewClient(mUIHandler));
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.clearHistory();
mWebView.clearFormData();
mWebView.clearCache(true);
WebSettings webSettings = mWebView.getSettings();
webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
Time time = new Time();
time.setToNow();
mWebView.loadUrl(mSocialProxy.getSignInURL()+"?time="+time.format("%Y%m%d%H%M%S"));
그래서 첫 번째 제안을 구현했습니다 (코드를 재귀 적으로 변경했지만)
private void clearApplicationCache() {
File dir = getCacheDir();
if (dir != null && dir.isDirectory()) {
try {
ArrayList<File> stack = new ArrayList<File>();
// Initialise the list
File[] children = dir.listFiles();
for (File child : children) {
stack.add(child);
}
while (stack.size() > 0) {
Log.v(TAG, LOG_START + "Clearing the stack - " + stack.size());
File f = stack.get(stack.size() - 1);
if (f.isDirectory() == true) {
boolean empty = f.delete();
if (empty == false) {
File[] files = f.listFiles();
if (files.length != 0) {
for (File tmp : files) {
stack.add(tmp);
}
}
} else {
stack.remove(stack.size() - 1);
}
} else {
f.delete();
stack.remove(stack.size() - 1);
}
}
} catch (Exception e) {
Log.e(TAG, LOG_START + "Failed to clean the cache");
}
}
}
그러나 이것은 여전히 페이지에 표시되는 내용을 변경하지 않았습니다. 내 데스크톱 브라우저에서 WebView에서 생성 된 웹 페이지와 다른 html 코드를 얻고 있으므로 WebView가 어딘가에 캐싱해야 함을 알고 있습니다.
IRC 채널에서 URL 연결에서 캐싱을 제거하는 수정 사항을 지적했지만 아직 WebView에 적용하는 방법을 볼 수 없습니다.
http://www.androidsnippets.org/snippets/45/
내 응용 프로그램을 삭제하고 다시 설치하면 웹 페이지를 캐시되지 않은 버전과 같은 최신 상태로 되돌릴 수 있습니다. 주요 문제는 웹 페이지의 링크가 변경되어 웹 페이지의 프런트 엔드가 완전히 변경되지 않는다는 것입니다.
답변
Gaunt Face가 게시 한 위의 편집 된 코드 스 니펫에는 파일 중 하나를 삭제할 수 없어 디렉토리가 삭제되지 않으면 코드가 무한 루프에서 계속 재 시도한다는 오류가 있습니다. 정말 재귀 적이되도록 다시 작성하고 numDays 매개 변수를 추가하여 정리할 파일의 수명을 제어 할 수 있습니다.
//helper method for clearCache() , recursive
//returns number of deleted files
static int clearCacheFolder(final File dir, final int numDays) {
int deletedFiles = 0;
if (dir!= null && dir.isDirectory()) {
try {
for (File child:dir.listFiles()) {
//first delete subdirectories recursively
if (child.isDirectory()) {
deletedFiles += clearCacheFolder(child, numDays);
}
//then delete the files and subdirectories in this dir
//only empty directories can be deleted, so subdirs have been done first
if (child.lastModified() < new Date().getTime() - numDays * DateUtils.DAY_IN_MILLIS) {
if (child.delete()) {
deletedFiles++;
}
}
}
}
catch(Exception e) {
Log.e(TAG, String.format("Failed to clean the cache, error %s", e.getMessage()));
}
}
return deletedFiles;
}
/*
* Delete the files older than numDays days from the application cache
* 0 means all files.
*/
public static void clearCache(final Context context, final int numDays) {
Log.i(TAG, String.format("Starting cache prune, deleting files older than %d days", numDays));
int numDeletedFiles = clearCacheFolder(context.getCacheDir(), numDays);
Log.i(TAG, String.format("Cache pruning completed, %d files deleted", numDeletedFiles));
}
다른 사람들에게 유용하기를 바랍니다. 🙂
답변
캐시 지우기에 대한 훨씬 우아하고 간단한 솔루션을 찾았습니다.
WebView obj;
obj.clearCache(true);
http://developer.android.com/reference/android/webkit/WebView.html#clearCache%28boolean%29
캐시를 지우는 방법을 알아 내려고 노력했지만 위에서 언급 한 방법으로 할 수있는 일은 로컬 파일을 제거하는 것이지만 RAM을 청소하지는 않습니다.
API clearCache는 웹보기에서 사용하는 RAM을 비우므로 웹 페이지를 다시로드해야합니다.
답변
찾고 있던 수정 사항을 찾았습니다.
context.deleteDatabase("webview.db");
context.deleteDatabase("webviewCache.db");
어떤 이유로 Android는 필요한 새 데이터 대신 실수로 계속 반환하는 URL의 잘못된 캐시를 만듭니다. 물론, DB에서 항목을 삭제할 수는 있지만 제 경우에는 하나의 URL에만 액세스하려고하므로 전체 DB를 날리는 것이 더 쉽습니다.
걱정하지 마세요. 이러한 DB는 앱과 연결되어 있으므로 전체 전화의 캐시를 지우지 않아도됩니다.
답변
앱에서 로그 아웃하는 동안 모든 웹뷰 캐시를 지우려면 :
CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
Lollipop 이상 :
CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookies(ValueCallback);
답변
웹뷰 캐시가있는 애플리케이션 캐시를 지워야합니다.
File dir = getActivity().getCacheDir();
if (dir != null && dir.isDirectory()) {
try {
File[] children = dir.listFiles();
if (children.length > 0) {
for (int i = 0; i < children.length; i++) {
File[] temp = children[i].listFiles();
for (int x = 0; x < temp.length; x++) {
temp[x].delete();
}
}
}
} catch (Exception e) {
Log.e("Cache", "failed cache clean");
}
}
답변
나를 위해 일하는 유일한 솔루션
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
CookieManager.getInstance().removeAllCookies(null);
CookieManager.getInstance().flush();
}
답변
Kotlin에서 아래 코드를 사용하면 효과적입니다.
WebView(applicationContext).clearCache(true)