BitmapFun示例应用程序中的图像缓存 - 这个检查背后的逻辑是什么?

4
我希望为图像实现内存和磁盘缓存。经过调查,我发现了这个链接和示例代码(您可以从右侧的链接下载)。 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的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);
}

附加问题: 有人在生产中使用这个代码吗? 这是个好主意吗?


希望这个链接能给你一些有关双重检查的提示:https://dev59.com/dG3Xa4cB1Zd3GeqPiL6c#14557132 - Moin Ahmed
其实并不是,但既然你是唯一一个努力帮忙的人,如果你发表答案,我会接受它。谢谢。 - Nemanja Kovacevic
你对于崩溃的处理怎么样了? - nucleons
好的,只需要检查它是否为空,然后如果是,则使用内部缓存。 - Nemanja Kovacevic
1个回答

1
发布自己的评论作为答案。它可能对其他人有帮助。:
getExternalStorageDirectory并不总是返回SD卡。这就是为什么实施安全检查的原因。
我曾经发布过类似的答案here,这是一个很好的实践方法,总是要检查它。
希望这能给你一些关于双重检查的提示。

那么关于这个崩溃,我们需要做些什么? - nucleons

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接