欢迎大家
我已经尝试过与此相关的每一个问题,在Stackoverflow和google中,它们都是无效的。我尝试过类似于下一个链接,但它返回与内部存储相同的内容:How to get an External storage sd card size (With Mounted SD card)?
例如,如果我有大约12 4GB的内部存储和4GB的SD卡存储,无论我使用什么方法,我总是得到与内部空间相同的SD空间的数字。
似乎这里发布在Stackoverflow中的旧方法只在Android中才起作用,而在下一个KitKat版本中却不起作用。
有可能解决这个问题吗?
发布于 2016-09-29 20:07:55
好吧,我一直在想这个问题,在网上找不到答案。所以我就是这么做的。可能没那么干净,但每次都对我有用。
对于我的例子:它返回61,055 MB。我有一个64 GB sd卡插入。
哦,我忘了说:我今天在三星Galaxy6.0和Sony Z5 Premium5.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();
}发布于 2016-09-29 20:31:16
我的手机内置存储容量为32 SD,SD卡为15 SD。在df上执行/mnt/sdcard会得到一个32 we的结果,这不是我们想要的结果。更进一步,我找到了这个/storage目录。里面有三个文件:
shell@E5803:/storage $ ls
8E5D-12E2
emulated
self对每一项执行df将给出以下结果:
shell@E5803:/storage $ df self
Filesystem Size Used Free Blksize
self 889.4M 0.0K 889.4M 4096
shell@E5803:/storage $ df emulated
Filesystem Size Used Free Blksize
emulated 22.6G 10.8G 11.8G 4096
shell@E5803:/storage $ df 8E5D-12E2/
Filesystem Size Used Free Blksize
8E5D-12E2/ 14.9G 2.3G 12.7G 32768我认为神奇的命令是"df /storage/" + mFilesArray[0],其中mFilesArray[]是ls /storage的结果。
(让我们希望谷歌的人不会在未来改变SD卡的安装点,我对此表示怀疑。)
希望这能有所帮助。
https://stackoverflow.com/questions/39777201
复制相似问题