内存中的文件缓存保存

时间:2014-07-19 10:23:27

标签: android image caching android-external-storage internal-storage

我开发了一个Android应用程序,它有从RSS提要检索的博客文章。
这篇文章包含博客文章的标题和图像 我正在使用以下代码保存图像缓存:

public class FileCache {

private File cacheDir;

public FileCache(Context context) {
    // Find the dir to save cached images
    if (android.os.Environment.getExternalStorageState().equals(
            android.os.Environment.MEDIA_MOUNTED))
        cacheDir = new File(
                android.os.Environment.getExternalStorageDirectory(),
                "LazyList");
    else
        cacheDir = context.getCacheDir();
    if (!cacheDir.exists())
        cacheDir.mkdirs();
}

public File getFile(String url) {
    // I identify images by hashcode. Not a perfect solution, good for the
    // demo.
    String filename = String.valueOf(url.hashCode());
    // Another possible solution (thanks to grantland)
    // String filename = URLEncoder.encode(url);
    File f = new File(cacheDir, filename);
    return f;

}

public void clear() {
    File[] files = cacheDir.listFiles();
    if (files == null)
        return;
    for (File f : files)
        f.delete();
}

}

但问题是它只在存储卡存在时保存缓存 我想要两个选项来保存缓存,即外部存储/内部存储

1 个答案:

答案 0 :(得分:0)

您只是检查getExternalStorage状态是否存在并且您仅在SD卡中创建了缓存目录...尝试使用以下条件:

final String cachePath =
        Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ||
                !isExternalStorageRemovable() ? getExternalCacheDir(context).getPath() :
                        context.getCacheDir().getPath();

return new File(cachePath + File.separator + uniqueName);