2012-03-16 104 views
7

如何使用PhoneGap和Android清除用戶數據或清除緩存?下面的代碼不起作用。我應該在哪裏進行更改;在HTML端還是在Java端?另外我正在訪問一個AJAX請求,並在PUT方法的第二次嘗試中,數據不會更新,所以我的主要嫌疑人是Android存儲的用戶數據。我在我的AJAX請求中添加了cache: false以確保它不存儲緩存。但它仍然不起作用。有想法該怎麼解決這個嗎?清除用戶數據或在Phonegap上清除緩存android

我有這個代碼基於另一個問題。

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(); 
} 
} 
+0

我會開始調試AJAX放置請求本身,因爲使用緩存:false,你永遠不會得到相同的響應兩次 - jQuery自動添加一個時間戳到這樣的請求,防止它被緩存 – 2012-08-14 10:38:24

+0

...另外,我也有成功地使用了上面提到的代碼來清除Android設備上的內部緩存,所以我猜這些代碼工作得很好 – 2012-08-14 10:39:31

回答

3

添加下面的代碼在你的OnCreate活動文件中的()方法加載的index.html後:

if (super.appView != null) { 
    super.appView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE); 
} 
1

我一直在尋找一種簡單的方法來清除緩存在我的科爾多瓦應用,並發現this plugin使用下面的代碼清除在Android的web視圖緩存:

// clear the cache 
self.webView.clearCache(true); 

而在iOS上,在後臺運行,並做到這一點:

[[NSURLCache sharedURLCache] removeAllCachedResponses]; 

使用插件,只需撥打window.CacheClear(success, error);

幸運的是,它解決了我的問題。 非常感謝這位cordova-plugin-cache-clear的作者!