004_01获取SD容量
1 package com.example.sdcard; 2 3 import java.io.File; 4 5 import android.app.Activity; 6 import android.os.Build; 7 import android.os.Bundle; 8 import android.os.Environment; 9 import android.os.StatFs; 10 import android.text.format.Formatter; 11 import android.view.Menu; 12 import android.view.MenuItem; 13 import android.widget.TextView; 14 15 public class MainActivity extends Activity { 16 17 private long blockSize; 18 private long totalBlocks; 19 private long availableBlocks; 20 21 @Override 22 protected void onCreate(Bundle savedInstanceState) { 23 super.onCreate(savedInstanceState); 24 setContentView(R.layout.activity_main); 25 26 TextView tv_available = (TextView) findViewById(R.id.tv_available); 27 TextView tv_total =(TextView) findViewById(R.id.tv_total); 28 29 File path = Environment.getExternalStorageDirectory(); 30 StatFs stat = new StatFs(path.getPath()); 31 32 if(Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2){ 33 blockSize = stat.getBlockSizeLong(); 34 totalBlocks = stat.getBlockCountLong(); 35 availableBlocks = stat.getAvailableBlocksLong(); 36 }else{ 37 blockSize = stat.getBlockSize(); 38 totalBlocks = stat.getBlockCount(); 39 availableBlocks = stat.getAvailableBlocks(); 40 } 41 42 //tv_available.setText(availableBlocks * blockSize + "/byte"); 43 //tv_total.setText(totalBlocks * blockSize + "/byte"); 44 45 String sdavail = formatSize(availableBlocks * blockSize); 46 String sdtotal = formatSize(totalBlocks * blockSize); 47 tv_available.setText(sdavail); 48 tv_total.setText(sdtotal); 49 50 } 51 private String formatSize(long size){ 52 return Formatter.formatFileSize(this, size); 53 } 54 }
物随心转,境由心造,一切烦恼皆由心生。