2014年7月11日 星期五

[Android] 使用UIL套件並將網路資源儲存在手機端

來源:eleZeta@flickr, CC BY-ND 2.0

前言
Android的開發者一定都知道Universal Image Loader (UIL)套件
也一定知道套件初始化的一些基本設置

1
2
3
4
5
 ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
                .discCacheExtraOptions(800, 800, CompressFormat.JPEG, 25, null)
                              .memoryCache(new WeakMemoryCache())
                              .threadPoolSize(5)
                              .build();

我這邊將預設圖片的長寬範圍在800x800以內, 壓縮率取到25%, 依據不同使用情況會有不同的設定.


問題
這樣子的設定並無法讓網路資源保存在手機上,
也就是說當app被關閉, 下次再開啟時又要再跟server要一次了.
如果這份資源不會有所變動,  我們又想節省server的負載以及手機的網路使用流量.
那就要考慮這樣的實作了.


實作
剛剛的config我們再增加一個discCache的設定
1
.discCache(new FileCountLimitedDiscCache(cacheDir, new Md5FileNameGenerator(), 500))

參數有cache路徑, file name, 以及cache資源的上限, 這裡設定500個項目.

好吧, 那cacheDir又要如何取得呢?
作者nostra13在github上有提到 (討論串)

1
2
3
4
5
6
7
8
9
File cacheDir;
if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
    // 偵測有SD卡
    cacheDir = new File(Environment.getExternalStorageDirectory(), "data/someapp/cache");
} else {
    // 偵測沒SD卡
    cacheDir = context.getCacheDir();
}
cacheDir.mkdirs();

在Activity中有 getFileDir() 和 getCacheDir() 這兩個方法
可以取得目前app在手機裡儲存空間的預設文件路徑
getFileDir() 對應到 /data/data/appname/files
getCacheDir() 對應到 /data/data/appname/cache

Returns the absolute path to the application specific cache directory on the filesystem. 
These files will be ones that get deleted first when the device runs low on storage
There is no guarantee when these files will be deleted. 
Note: you should not rely on the system deleting these files for you; 
you should always have a reasonable maximum, such as 1 MB, 
for the amount of space you consume with cache files, and prune those files when exceeding that space.

官方文件對 getCacheDir() 的使用也有溫馨的提醒
除存在cache的資料會在系統偵測空間不足時首先被移除,
所以系統不保證什麼時候會做刪除動作, 開發者也不應該依賴這個機制.
而是應該設置個合理的cache上限, 然後在超過時進行資料刪減的動作.

當然也要記得在project的Manifest檔裡面設定SD卡的存取權限
<!-- if you want to allow UIL to cache images on SD card -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Evernote helps you remember everything and get organized effortlessly. Download Evernote.

沒有留言:

張貼留言

內容回應