在Phonegap Android上清除用户数据或清除缓存

7
如何使用PhoneGap和Android清除用户数据或清除缓存?下面的代码无效。我应该在HTML端还是Java端进行更改?此外,我正在访问一个AJAX请求,并且在第二次尝试PUT方法时,数据不会更新,因此我的主要嫌疑人是Android存储的用户数据。我已经在我的AJAX请求中添加了cache: false以确保它不存储缓存。但它仍然不起作用。有没有想法如何解决这个问题?
我有这段代码,基于另一个问题。
public static void deleteCache(Context context) {
    try {
        File dir = context.getCacheDir();
        if (dir != null && dir.isDirectory()) {
            deleteDir(dir);
        }
    } catch (Exception e) {}
}

public static boolean deleteDir(File dir) {
    if (dir != null && dir.isDirectory()) {
        String[] children = dir.list();
        for (int i = 0; i < children.length; i++) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
        }
    }
    return dir.delete();
}

所以基本上我的POSActivity.java看起来会像这样。
public class PocActivity extends DroidGap {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    super.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    super.setIntegerProperty("splashscreen", R.drawable.is);
    super.setIntegerProperty("loadUrlTimeoutValue", 60000);
    deleteCache(this);
    super.loadUrl("file:///android_asset/www/index.html");
}

public static void deleteCache(Context context) {
    try {
        File dir = context.getCacheDir();
        if (dir != null && dir.isDirectory()) {
            deleteDir(dir);
        }
    } catch (Exception e) {}
}

public static boolean deleteDir(File dir) {
    if (dir != null && dir.isDirectory()) {
        String[] children = dir.list();
        for (int i = 0; i < children.length; i++) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
        }
    }
    return dir.delete();
}
}

我会从调试 AJAX put 请求本身开始,因为使用 cache:false,你不应该两次得到相同的响应 - jQuery 会自动向这样的请求添加时间戳,防止其被缓存。 - Zathrus Writer
此外,我已成功使用上述代码清除 Android 设备上的内部缓存,因此我想那段代码应该可以正常工作。 - Zathrus Writer
2个回答

3
在activity文件的oncreate()方法中加载index.html后,添加以下代码:
if (super.appView != null) {
     super.appView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
}

1
我在寻找一种简单的方式来清除我的 Cordova 应用程序中的缓存,并找到了 这个插件,它使用以下代码来清除 Android 中的 webView 缓存:
// clear the cache
self.webView.clearCache(true);

在iOS中,可以在后台运行并执行以下操作:
[[NSURLCache sharedURLCache] removeAllCachedResponses];

要使用插件,只需调用window.CacheClear(success, error);

对我来说很幸运,它解决了我遇到的问题。 非常感谢cordova-plugin-cache-clear的作者!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接