如何知道appcache何时完成?

时间:2012-03-06 13:10:34

标签: android html5 android-webview

有没有办法知道webview何时缓存了HTML5清单所请求的文件?

这是我正在做的事情,但离线时可能会显示不完整的显示(缺少一些图像)

//v is my WebView instance
String cachePath = "/data/data/"+getPackageName()+"/cache";
v.getSettings().setAppCachePath(cachePath);
v.getSettings().setAppCacheMaxSize(1024*1024*4); // 4Mo default cache size
v.getSettings().setAllowFileAccess(true);
v.getSettings().setAppCacheEnabled(true);
v.getSettings().setDomStorageEnabled(true);

ConnectivityManager cm = (ConnectivityManager)this.getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo netInfos = cm.getActiveNetworkInfo();
if(null != netInfos && netInfos.isConnected()) {
    v.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
}
else {
    File f = new File(cachePath);
    if(f.exists()){
        v.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ONLY);
    }
    else{
        url = fallbackUrl;
    }
}

我希望在缓存完成时得到通知,或者更好地了解缓存目录是否“已损坏”。

1 个答案:

答案 0 :(得分:0)

原始海报将此作为问题的更新,但它确实是一个答案,所以我在这里移动:

原始海报的所有剩余内容

感谢robertc的建议,这就是我现在正在做的事情:

在JS方面,我正在侦听缓存事件。 当它被触发时,我在我的JS接口上调用一个方法,在android缓存文件夹中创建一个文件“cachepresent.dummy”。通过测试这个文件是否存在,我可以通过android方面知道缓存是否完整。 使用相同的机制我在触发updateready事件时清除整个android缓存文件夹。

这是java代码:

private class JsInterface {

    public JsInterface() {}

    @SuppressWarnings("unused")
    public void cached() {
        File f = new File("/data/data/"+getPackageName()+"/cache/cachepresent.dummy");
        FileWriter w;
        try {
            w = new FileWriter(f);
            w.close();
        } 
        catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void DeleteRecursive(File f) {
        if (f.isDirectory()) {
            for (File child : f.listFiles()) {
                DeleteRecursive(child);
            }
        }
        f.delete();
    }

    @SuppressWarnings("unused")
    public void clearCache(){
        File f = new File("/data/data/"+getPackageName()+"/cache");
        DeleteRecursive(f);
    }

}
...
//add the javascript interface to the webview
jsInterface = new JsInterface();
v.addJavascriptInterface(jsInterface, "JsBridge");

//Check if the cache is complete
File cachePresentFile = new File("/data/data/"+getPackageName()+"/cache/cachepresent.dummy");
boolean cachePresent = cachePresentFile.exists();

JS代码:

    function cacheReload() {
        var cache = window.applicationCache;
        try{
            cache.update();
        }
        catch(e){
            //android 2.2 does not seem to support this :'(
            console.log("JS Exception: " + e);
        }
        cache.addEventListener("updateready",
            function () {
                JsBridge.clearCache();
                cache.swapCache();
                window.location.reload();
            }
        );

        cache.addEventListener("cached",
            function () {
                JsBridge.cached();
            }
        );
    }

BTW我很确定通过使用HTML5 LocalStorage的东西可以实现这一目标。