我想为图像实现内存和磁盘缓存。调查我找到了这个链接和示例代码(您可以从右侧的链接下载)
http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html
代码中某处有这个方法:
/**
* 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);
}
我想知道这项检查背后的基本原理是什么:
Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ||
!isExternalStorageRemovable()
第二部分对我来说似乎是多余的。这可以理解为“即使未安装外部存储也让我们使用它,因为它无法删除”但显然您不能将其用于缓存,因为它未安装。
使用这段代码在模拟器上发生了有趣的事情。它在基于 Galaxy Nexus 和未指定 SD 卡的 AVD 上崩溃。第一部分将返回 false(它将其视为“已删除”),第二部分将返回 true(因为“外部”存储在 GN 上不可移动)。因此它会尝试使用外部存储,但由于无法使用它会崩溃。
我已经用我的 Galaxy Nexus 进行了测试,以了解当手机连接到 pa PC 或 Mac 时的第一个部分值是多少,并且两次都是如此。它仍处于安装状态,但 PC 或 Mac 仍然可以写入。
如果您需要它们,这里是上面代码中使用的其他方法:
/**
* 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 (Utils.hasGingerbread()) {
return Environment.isExternalStorageRemovable();
}
return true;
}
/**
* Get the external app cache directory.
*
* @param context The context to use
* @return The external cache dir
*/
@TargetApi(8)
public static File getExternalCacheDir(Context context) {
if (Utils.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);
}
奖励问题:是否有人在生产中使用此代码?这是个好主意吗?
最佳答案
发表我自己的评论作为答案。这可能对其他人有帮助。 :
getExternalStorageDirectory 并不总是返回 SDCard。这就是实现安全检查的原因。
我发布了类似的答案 here始终检查它是一种很好的做法。
希望这会给你一些关于双重检查的提示。
关于android - BitmapFun 示例应用程序中的图像缓存 - 此检查背后的基本原理是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14567650/