如何检查android设备上的可用空间?在SD卡上?

如何查看Android设备上还剩下多少MB或GB?我正在使用JAVA和android SDK 2.0.1。

是否有任何系统服务会公开这样的信息?


函数式编程
浏览 527回答 3
3回答

holdtom

试试这个代码: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() -返回普通程序仍可访问的块数(感谢乔)

桃花长相依

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);}上面的代码引用了一些不推荐使用的功能。下面我复制一个更新的版本: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);}

吃鸡游戏

我设计了一些现成的函数来获取不同单位的可用空间。您可以通过简单地将其中任何一种复制到项目中来使用这些方法。/** * @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;}
打开App,查看更多内容
随时随地看视频慕课网APP