查询存储空间的代码
16lz
2021-01-24
以下代码片段转载自Android Snippets
该代码片段可以让我们获取internal和external的存储空间大小。
1. import java.io.File; 2. 3. import android.os.Environment; 4. import android.os.StatFs; 5. 6. public class MemoryStatus { 7. 8. static final int ERROR = -1; 9. 10. static public boolean externalMemoryAvailable() { 11. return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); 12. } 13. 14. static public long getAvailableInternalMemorySize() { 15. File path = Environment.getDataDirectory(); 16. StatFs stat = new StatFs(path.getPath()); 17. long blockSize = stat.getBlockSize(); 18. long availableBlocks = stat.getAvailableBlocks(); 19. return availableBlocks * blockSize; 20. } 21. 22. static public long getTotalInternalMemorySize() { 23. File path = Environment.getDataDirectory(); 24. StatFs stat = new StatFs(path.getPath()); 25. long blockSize = stat.getBlockSize(); 26. long totalBlocks = stat.getBlockCount(); 27. return totalBlocks * blockSize; 28. } 29. 30. static public long getAvailableExternalMemorySize() { 31. if(externalMemoryAvailable()) { 32. File path = Environment.getExternalStorageDirectory(); 33. StatFs stat = new StatFs(path.getPath()); 34. long blockSize = stat.getBlockSize(); 35. long availableBlocks = stat.getAvailableBlocks(); 36. return availableBlocks * blockSize; 37. } else { 38. return ERROR; 39. } 40. } 41. 42. static public long getTotalExternalMemorySize() { 43. if(externalMemoryAvailable()) { 44. File path = Environment.getExternalStorageDirectory(); 45. StatFs stat = new StatFs(path.getPath()); 46. long blockSize = stat.getBlockSize(); 47. long totalBlocks = stat.getBlockCount(); 48. return totalBlocks * blockSize; 49. } else { 50. return ERROR; 51. } 52. } 53. 54. static public String formatSize(long size) { 55. String suffix = null; 56. 57. if (size >= 1024) { 58. suffix = "KiB"; 59. size /= 1024; 60. if (size >= 1024) { 61. suffix = "MiB"; 62. size /= 1024; 63. } 64. } 65. 66. StringBuilder resultBuffer = new StringBuilder(Long.toString(size)); 67. 68. int commaOffset = resultBuffer.length() - 3; 69. while (commaOffset > 0) { 70. resultBuffer.insert(commaOffset, ','); 71. commaOffset -= 3; 72. } 73. 74. if (suffix != null) 75. resultBuffer.append(suffix); 76. return resultBuffer.toString(); 77. } 78. }
更多相关文章
- 在AndroidStudio中使用V8包中的RenderScript
- UI 开源代码 FileBrowserView
- Android系列教程:TextView小组件的使用--附带超链接和跑马灯效果
- Android番外03_Umeng友盟统计集成
- Android(安卓)列表按照时间排序
- Android客户端对服务端返回的xml文件内容进行解析
- android Intent的一些用法
- flutter配置高德地图SDK
- Android(安卓)remake