android之读取SD卡状态

package xidian.dy.com.chujia;

import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.Formatter;
import android.widget.TextView; import java.io.File; public class MainActivity extends AppCompatActivity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
TextView tv1 = (TextView)findViewById(R.id.total);
TextView tv2 = (TextView)findViewById(R.id.available);
File f = Environment.getExternalStorageDirectory();
StatFs stat = new StatFs(f.getPath());
long blockSize,totalBlocks,availableBlocks;
if(Build.VERSION.SDK_INT >=Build.VERSION_CODES.JELLY_BEAN_MR2){
blockSize = stat.getBlockSizeLong();
totalBlocks = stat.getBlockCountLong();
availableBlocks = stat.getAvailableBlocksLong();
}else {
blockSize = stat.getBlockSize();
totalBlocks = stat.getBlockCount();
availableBlocks = stat.getAvailableBlocks();
}
if(tv1 != null)
tv1.setText("总大小:"+formatSize(blockSize*totalBlocks));
if(tv2 != null)
tv2.setText("剩余容量:"+formatSize(blockSize*availableBlocks));
}
} private String formatSize(long size){
return Formatter.formatFileSize(this, size);
}
}

在查看SD卡容量的时候首先看SD卡是否挂载,如果已挂载则再检查系统的版本。根据不同的版本调用不同的系统API。计算SD卡容量的时候是根据每个区块的大小*总区块个数来计算的。FormatFileSize函数是将字节转换为MB/GB。

上一篇:java的版本区别、下载、配置


下一篇:js获取页面元素距离浏览器工作区顶端的距离