欢迎大家
我已经在 Stackoverflow 和 google 上尝试过与此相关的每个问题,但没有一个有效。我已经尝试过类似下一个链接的操作,但它返回的内容与内部存储相同:如何获取外部存储 SD 卡的大小(带安装的 SD 卡)? https://stackoverflow.com/questions/16834964/how-to-get-an-external-storage-sd-card-size-with-mounted-sd-card/16835201#16835201
例如,如果我有大约 12GB 内部存储和 4GB SD 卡存储,无论我使用什么方法,我总是得到与内部空间完全相同的 SD 空间数字。
看来 Stackoverflow 中发布的旧方法仅适用于 Android KitKat,但不适用于下一个 Android 版本。
有可能解决这个问题吗?
好吧,我一直想知道这个问题,但在网上找不到答案。这就是我所做的。它可能不是那么干净,但每次都对我有用。
对于我的情况:它返回 61,055 MB。我插入了 64 GB 的 SD 卡。
哦,我忘了提及:我这样做是在三星 Galaxy S5 6.0 and 索尼 Xperia Z5 Premium 5.1.1今天确认一下。但是,我还有一个每天有几百人使用的应用程序,而且我还没有遇到任何问题。
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
static String getExternalSdCardSize() {
File storage = new File("/storage");
String external_storage_path = "";
String size = "";
if (storage.exists()) {
File[] files = storage.listFiles();
for (File file : files) {
if (file.exists()) {
try {
if (Environment.isExternalStorageRemovable(file)) {
// storage is removable
external_storage_path = file.getAbsolutePath();
break;
}
} catch (Exception e) {
Log.e("TAG", e.toString());
}
}
}
}
if (!external_storage_path.isEmpty()) {
File external_storage = new File(external_storage_path);
if (external_storage.exists()) {
size = totalSize(external_storage);
}
}
return size;
}
private static String totalSize(File file) {
StatFs stat = new StatFs(file.getPath());
long blockSize, totalBlocks;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
blockSize = stat.getBlockSizeLong();
totalBlocks = stat.getBlockCountLong();
} else {
blockSize = stat.getBlockSize();
totalBlocks = stat.getBlockCount();
}
return formatSize(totalBlocks * blockSize);
}
private static String formatSize(long size) {
String suffix = null;
if (size >= 1024) {
suffix = "KB";
size /= 1024;
if (size >= 1024) {
suffix = "MB";
size /= 1024;
}
}
StringBuilder resultBuilder = new StringBuilder(Long.toString(size));
int commaOffset = resultBuilder.length() - 3;
while (commaOffset > 0) {
resultBuilder.insert(commaOffset, ',');
commaOffset -= 3;
}
if (suffix != null) resultBuilder.append(suffix);
return resultBuilder.toString();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)