在缓存数据的时,有时候会出现没有外部存储设备的情况,所以需要检测是否存在外部存储设备
/** * 检测外部存储设备 * * @param requireWriteAccess * @return */ public static boolean hasStorage(boolean requireWriteAccess) { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { if (requireWriteAccess) { boolean writable = checkFsWritable(); return writable; } else { return true; } } else if (!requireWriteAccess && Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { return true; } return false; }
private static boolean checkFsWritable() { // Create a temporary file to see whether a volume is really writeable. // It's important not to put it in the root directory which may have a // limit on the number of files. String directoryName = Environment.getExternalStorageDirectory() .toString() + "/DCIM"; File directory = new File(directoryName); if (!directory.isDirectory()) { if (!directory.mkdirs()) { return false; } } File f = new File(directoryName, ".probe"); try { // Remove stale file if any if (f.exists()) { f.delete(); } if (!f.createNewFile()) { return false; } f.delete(); return true; } catch (IOException ex) { return false; } }