6

I have an Android browser and I have the option to clear cache, storage, cookies, etc.

The code looks like this:

webView.clearCache(true);
webView.clearFormData();
webView.clearHistory();
webView.clearSslPreferences();
CookieManager.getInstance().removeAllCookies(null);
CookieManager.getInstance().flush();

And this seems to work on all my tests but when I go to google.com my old searches are still there. What am I not clearing?

Thanks.

casolorz
  • 8,486
  • 19
  • 93
  • 200
  • I'm not sure if it is the same like `removeAllCookies`, but can you try `CookieManager.getInstance().removeSessionCookie();`? – Julian Schmuckli Jun 12 '17 at 14:54
  • 1
    Found the solution `WebStorage.getInstance().deleteAllData();` – casolorz Jun 12 '17 at 15:49
  • @casolorz please have a look at my answer –  Oct 19 '17 at 11:12
  • I have no issues with `deleteAllData()` and have never had a crash report from that on crashlytics with hundreds of thousands of the users using this app. – casolorz Oct 19 '17 at 14:26
  • Hi! What's the purpose of calling CookieManager.getInstance().flush(); ? according to documentation https://developer.android.com/reference/android/webkit/CookieManager.html#flush() it's not related to clearing cookies... – hhg Nov 10 '17 at 19:58
  • I don't remember, I think I copied this code from somewhere else. I guess the idea might be that this makes sure to save the store to disk while blocking access to it. – casolorz Nov 10 '17 at 20:02

2 Answers2

16

Found the solution:

WebStorage.getInstance().deleteAllData();
casolorz
  • 8,486
  • 19
  • 93
  • 200
1

I have got a root-access granted device and found that calling WebStorage.getInstance().deleteAllData(); and similar codes doesn't clear the cache created by the WebView at applicationDatadir/app_webview.

Also, that codes sometimes causes fatal errors like A/libc: Send stop signal to pid:16145 in void debuggerd_signal_handler(int, siginfo_t*, void*)

And it's (the cache) not so small in size.

To achieve that you can use this following code snippet :

public static void clearWebViewCachesCustom(Context context) {
    try {
        String dataDir = mContext.getPackageManager().getPackageInfo(context.getPackageName(), 0).applicationInfo.dataDir;
        new File(dataDir + "/app_webview/").delete();
    } catch (Exception e) {
        if (!MainActivity.deBugTest) Crashlytics.logException(e);
        e.printStackTrace();
        e.getSuppressed();
    }
}
  • Why do you need all these tricks, `getContext().getApplicationInfo().dataDir` is the documented way to get it. – Alex Cohn Feb 23 '21 at 16:35
  • 1
    On the other hand, you must delete all files and subfolders of `app_webview`; luckily, in Kotlin you have `File.deleteRecursively()` – Alex Cohn Feb 23 '21 at 17:59