当前位置:操作系统 > 安卓/Android >>

获取Android手机中SD卡内存信息

访问sdcard的权限:
[java] 
1. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission> 

[java] 
1. btn.setOnClickListener(new View.OnClickListener() { 
2.  
3.              
4.             @Override 
5.             public void onClick(View v) { 
6.                 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { 
7.                     //取得sdcard文件路径 
8.                     File path = Environment.getExternalStorageDirectory(); // "mnt/sdcard" 
9.                     path = new File("mnt/extsd"); 
10.                     Log.i("chens", "======path========"+path); 
11.                     StatFs statfs = new StatFs(path.getPath()); 
12.                      
13.                     //获取block的SIZE 
14.                     long blocSize = statfs.getBlockSize(); 
15.                      
16.                     //获取BLOCK数量 
17.                     long totalBlocks = statfs.getBlockCount(); 
18.                      
19.                     //空闲的Block的数量 
20.                     long availaBlock = statfs.getAvailableBlocks(); 
21.                      
22.                     //计算总空间大小和空闲的空间大小 
23.                     String[] total = filesize(totalBlocks * blocSize); 
24.                     String[] availale = filesize(availaBlock * blocSize); 
25.                      
26.                     Toast.makeText(FirstActivity.this, "sdcard总空间大小="+total[0]+total[1] 
27.                             +"\n剩余空间大小="+availale[0]+availale[1], 1).show(); 
28.                 }else { 
29.                     Toast.makeText(FirstActivity.this, "没有sdcard或者sdcard挂载失败", 1).show(); 
30.                 } 
31.                  
32.                  
33.                  
34.                  
35.  
36.             } 
37.         }); 
38.     } 

[java] 
1. //计算空间方法csize 
2.     String[] filesize(long size) {  
3.         String str = "";  
4.         if (size >= 1024) {  
5.             str = "KB";  
6.             size /= 1024;  
7.             if (size >= 1024) {  
8.                 str = "MB";  
9.                 size /= 1024;  
10.             }    www.zzzyk.com
11.         } 
12.         DecimalFormat formatter = new DecimalFormat();  
13.         formatter.setGroupingSize(3);  
14.         String result[] = new String[2];  
15.         result[0] = formatter.format(size);  
16.         result[1] = str;  
17.         return result;  
18.     } 


 

作者:chenshijun0101
补充:移动开发 , Android ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,