如何检查Android设备上的可用空间?SD卡上的可用空间?[duplicate]

iovurdzv  于 2022-12-16  发布在  Android
关注(0)|答案(9)|浏览(171)

此问题在此处已有答案

(13个答案)
5年前关闭。
如何查看Android设备上的剩余空间(MB或GB)?我使用的是Java和Android SDK 2.0.1。
是否有系统服务会公开这样的内容?

nxowjjhe

nxowjjhe1#

Yaroslav的答案给予了SD卡的大小,而不是可用空间,StatFs的getAvailableBlocks()将返回正常程序仍然可以访问的块的数量,下面是我使用的函数:

public static float megabytesAvailable(File f) {
    StatFs stat = new StatFs(f.getPath());
    long bytesAvailable = (long)stat.getBlockSize() * (long)stat.getAvailableBlocks();
    return bytesAvailable / (1024.f * 1024.f);
}

上述代码引用了一些自2014年8月13日起已弃用的函数。我在下面重现了更新版本:

public static float megabytesAvailable(File f) {
    StatFs stat = new StatFs(f.getPath());
    long bytesAvailable = 0;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2)
        bytesAvailable = (long) stat.getBlockSizeLong() * (long) stat.getAvailableBlocksLong();
    else
        bytesAvailable = (long) stat.getBlockSize() * (long) stat.getAvailableBlocks();
    return bytesAvailable / (1024.f * 1024.f);
}
o75abkj4

o75abkj42#

尝试this code

StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());

long bytesAvailable = (long)stat.getBlockSize() *(long)stat.getBlockCount();
long megAvailable   = bytesAvailable / 1048576;

System.out.println("Megs: " + megAvailable);

解释

getBlockCount()--SD卡返回大小;
getAvailableBlocks()-返回正常程序仍可访问的块的数量(谢谢Joe)

pcww981p

pcww981p3#

我已经设计了一些现成的函数来获取不同单位的可用空间。你可以通过简单地将它们中的任何一个复制到你的项目中来使用这些方法。

/**
 * @return Number of bytes available on External storage
 */
public static long getAvailableSpaceInBytes() {
    long availableSpace = -1L;
    StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
    availableSpace = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize();

    return availableSpace;
}

/**
 * @return Number of kilo bytes available on External storage
 */
public static long getAvailableSpaceInKB() {
    final long SIZE_KB = 1024L;
    long availableSpace = -1L;
    StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
    availableSpace = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize();
    return availableSpace/SIZE_KB;
}

/**
 * @return Number of Mega bytes available on External storage
 */
public static long getAvailableSpaceInMB() {
    final long SIZE_KB = 1024L;
    final long SIZE_MB = SIZE_KB * SIZE_KB;
    long availableSpace = -1L;
    StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
    availableSpace = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize();
    return availableSpace/SIZE_MB;
}

/**
 * @return Number of gega bytes available on External storage
 */
public static long getAvailableSpaceInGB() {
    final long SIZE_KB = 1024L;
    final long SIZE_GB = SIZE_KB * SIZE_KB * SIZE_KB;
    long availableSpace = -1L;
    StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
    availableSpace = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize();
    return availableSpace/SIZE_GB;
}
ztyzrc3y

ztyzrc3y4#

基于this answer,他们增加了对Android版本〈18:

public static float megabytesAvailable(File file) {
    StatFs stat = new StatFs(file.getPath());
    long bytesAvailable;
    if(Build.VERSION.SDK_INT >= 18) {
        bytesAvailable = getAvailableBytes(stat);
    }
    else {
        // noinspection deprecation
        bytesAvailable = stat.getBlockSize() * stat.getAvailableBlocks();
    }

    return bytesAvailable / (1024.f * 1024.f);
}

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
private static long getAvailableBytes(StatFs stat) {
    return stat.getBlockSizeLong() * stat.getAvailableBlocksLong();
}
quhf5bfb

quhf5bfb5#

自API版本18起引入了新方法。
我使用类似的方法来估计大磁盘缓存大小(Picasso OkHttp下载器缓存)。

private static final String BIG_CACHE_PATH = "my-cache-dir";
private static final float  MAX_AVAILABLE_SPACE_USE_FRACTION = 0.9f;
private static final float  MAX_TOTAL_SPACE_USE_FRACTION     = 0.25f;

static File createDefaultCacheDirExample(Context context) {
    File cache = new File(context.getApplicationContext().getCacheDir(), BIG_CACHE_PATH);
    if (!cache.exists()) {
        cache.mkdirs();
    }
    return cache;
}

/**
 * Calculates minimum of available or total fraction of disk space
 * 
 * @param dir
 * @return space in bytes
 */
@SuppressLint("NewApi")
static long calculateAvailableCacheSize(File dir) {
    long size = 0;
    try {
        StatFs statFs = new StatFs(dir.getAbsolutePath());
        int sdkInt = Build.VERSION.SDK_INT;
        long totalBytes;
        long availableBytes;
        if (sdkInt < Build.VERSION_CODES.JELLY_BEAN_MR2) {
            int blockSize = statFs.getBlockSize();
            availableBytes = ((long) statFs.getAvailableBlocks()) * blockSize;
            totalBytes = ((long) statFs.getBlockCount()) * blockSize;
        } else {
            availableBytes = statFs.getAvailableBytes();
            totalBytes = statFs.getTotalBytes();
        }
        // Target at least 90% of available or 25% of total space
        size = (long) Math.min(availableBytes * MAX_AVAILABLE_SPACE_USE_FRACTION, totalBytes * MAX_TOTAL_SPACE_USE_FRACTION);
    } catch (IllegalArgumentException ignored) {
        // ignored
    }
    return size;
}
cqoc49vn

cqoc49vn6#

此外,如果要检查内部存储器上的可用空间,请用途:

File path = Environment.getDataDirectory();
StatFs stat = new StatFs(path.getPath());

...

mitkmikd

mitkmikd7#

Google has information on this on the getting started page-请参阅查询可用空间。他们说您可以通过getFreeSpace()检查可用空间,但他们指出这是不准确的,您应该期望比这少一点的可用空间。他们说:
如果返回的数字比您要保存的数据大几MB,或者文件系统的使用率低于90%,则可能可以安全地继续。否则,您可能不应该写入存储。
此外,他们给予,它往往更有用的不是检查可用空间在所有和只是trycatch的错误:
在保存文件之前,您不需要检查可用空间的大小。您可以尝试立即写入文件,然后在发生IOException时捕获IOException。如果您不确切知道需要多少空间,则可能需要执行此操作。例如,如果您在保存文件之前通过将PNG图像转换为JPEG来更改文件的编码,则无法事先知道文件的大小。
我建议只有对于非常大的文件,你才应该事先检查可用的存储空间,这样你就不会浪费时间下载或创建一个文件,如果明显太大,容纳。在任何情况下,你都应该总是使用trycatch,所以我认为唯一的理由是事先检查可用的空闲空间,如果是不必要的使用资源和时间太多。

2uluyalo

2uluyalo8#

这段代码已经过测试,工作正常。

/**
 * Get the free disk available space in boolean to download requested file 
 * 
 * @return boolean value according to size availability
 */

protected static boolean isMemorySizeAvailableAndroid(long download_bytes, boolean isExternalMemory) {
    boolean isMemoryAvailable = false;
    long freeSpace = 0;
    
    // if isExternalMemory get true to calculate external SD card available size
    if(isExternalMemory){
        try {
            StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
            freeSpace = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize();
            if(freeSpace > download_bytes){
                isMemoryAvailable = true;
            }else{
                isMemoryAvailable = false;
            }
        } catch (Exception e) {e.printStackTrace(); isMemoryAvailable = false;}
    }else{
        // find phone available size
        try {
            StatFs stat = new StatFs(Environment.getDataDirectory().getPath());
            freeSpace = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize();
            if(freeSpace > download_bytes){
                isMemoryAvailable = true;
            }else{
                isMemoryAvailable = false;
            }
        } catch (Exception e) {e.printStackTrace(); isMemoryAvailable = false;}
    }
    
    return isMemoryAvailable;
}
cfh9epnr

cfh9epnr9#

public String TotalExtMemory()
{
    StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());   
    int Total = (statFs.getBlockCount() * statFs.getBlockSize()) / 1048576;

    String strI = Integer.toString(Total);
    return strI;
}

public String FreeExtMemory()
{
    StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());
    int Free  = (statFs.getAvailableBlocks() * statFs.getBlockSize()) / 1048576;
    String strI = Integer.toString(Free);
    return strI;
}

public String BusyExtMemory()
{
    StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());   
    int Total = (statFs.getBlockCount() * statFs.getBlockSize()) / 1048576;
    int Free  = (statFs.getAvailableBlocks() * statFs.getBlockSize()) / 1048576;
    int Busy  = Total - Free;
    String strI = Integer.toString(Busy);
    return strI;
}

相关问题