標籤:android style java 檔案 os 資料
今天晚上,產品經理打電話說我們的Android App除了問題,問題很簡單就是一個緩衝問題,由於這個程式是前同事寫的,我也只能呵呵一笑,有些事你就得扛。還是回到正題吧,這個緩衝問題,實在有點奇葩,所以我才要記錄下,希望避免
問題
看了代碼,感覺上沒問題,不過針對使用者出現的問題,還是覺得這個邏輯就是錯誤的:
1 有檔案快取就不在請求網路
由於請求的那個介面返回的資料較大,做了一個檔案快取放到本地,這個沒錯,可是緩衝完後,當下次在請求,居然先判斷快取檔案是否存在,若存在就不在讀取網路資料,而是直接用了快取檔案的資料—————— 你能保證,你緩衝的資料就不在變化嗎?你能保證,你緩衝的資料就是正確的嗎?
2 快取檔案時放到SDCard下
快取檔案一般系統提供的都有相關的目錄,當應用程式被卸載了,這個緩衝目錄也就不存在了,這為使用者節省了大量的儲存空間。可是你放到SD卡是個什麼意思?卸載了,這個檔案還在!!!!!
解決辦法
問題有了,那就該解決,每次訪問網路都要讀取網路資料,檢驗下資料是否是正確的,只有正確了再緩衝。
快取檔案放到緩衝目錄下,為此,還將BitmapFun項目的一個類給借過來了,也一併帖出來吧:
import android.annotation.TargetApi;import android.content.Context;import android.os.Environment;/** * 裡面存放的是關於路徑的一些helper類 * @author Cyning * @date 2014-7-10 上午9:57:12 */public class PathUtil { /** * Get a usable cache directory (external if available, internal otherwise). * * @param context The context to use * @param uniqueName A unique directory name to append to the cache dir * @return The cache dir */ public static File getDiskCacheDir(Context context, String uniqueName) { // Check if media is mounted or storage is built-in, if so, try and use external cache dir // otherwise use internal cache dir final String cachePath = Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !isExternalStorageRemovable() ? getExternalCacheDir(context).getPath() : context.getCacheDir().getPath(); return new File(cachePath + File.separator + uniqueName); } /** * Check if external storage is built-in or removable. * * @return True if external storage is removable (like an SD card), false * otherwise. */ @TargetApi(9) public static boolean isExternalStorageRemovable() { if (CompatUtils.hasGingerbread()) { return Environment.isExternalStorageRemovable(); } return true; } @TargetApi(8) public static File getExternalCacheDir(Context context) { if (CompatUtils.hasFroyo()) { return context.getExternalCacheDir(); } // Before Froyo we need to construct the external cache dir ourselves final String cacheDir = "/Android/data/" + context.getPackageName() + "/cache/"; return new File(Environment.getExternalStorageDirectory().getPath() + cacheDir); }}