我希望为图像实现内存和磁盘缓存。经过调查,我发现了这个链接和示例代码(您可以从右侧的链接下载)。
http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html
代码中有一个方法:
我想知道这个检查的原理是什么:
第二部分内容对我来说似乎有点多余。这可以理解为“即使外部存储未挂载,让我们使用它,因为它不能被移除”,但显然你不能将其用于缓存,因为它没有挂载。
在模拟器上使用此代码时会出现有趣的问题。基于Galaxy Nexus的AVD未指定SD卡时会崩溃。第一部分将返回false(它将其视为“已删除”),第二部分将返回true(因为GN上的“外部”存储不可移除)。因此,它将尝试使用外部存储,并且将崩溃,因为无法使用它。
我已经使用我的Galaxy Nexus进行了测试,以查看手机连接到PC或Mac时的第一部分值,在这两种情况下它都为true。它仍然已挂载,但PC或Mac仍然可以写入它。
如果您需要它们,以下是上述代码中使用的其他方法:
/**
* 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的AVD未指定SD卡时会崩溃。第一部分将返回false(它将其视为“已删除”),第二部分将返回true(因为GN上的“外部”存储不可移除)。因此,它将尝试使用外部存储,并且将崩溃,因为无法使用它。
我已经使用我的Galaxy Nexus进行了测试,以查看手机连接到PC或Mac时的第一部分值,在这两种情况下它都为true。它仍然已挂载,但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);
}
附加问题: 有人在生产中使用这个代码吗? 这是个好主意吗?