<h2 name="code" class="java">import java.io.File;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.text.format.Formatter;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// [1]找到我们关心的控件
TextView tv_total_size = (TextView) findViewById(R.id.textView1);
TextView tv_useable_size = (TextView) findViewById(R.id.textView3);
// [2]要获取sd卡的容量 也通过 Environment
File file = Environment.getExternalStorageDirectory();
long totalSpace = file.getTotalSpace(); // 返回总大小 以字节为单位
long usableSpace = file.getUsableSpace();
// [3]要把获取的totalSpace 和 usableSpace转换单位
String totalSpaceSize = Formatter.formatFileSize(getApplicationContext(), totalSpace);
String usableSpaceSize = Formatter.formatFileSize(getApplicationContext(), usableSpace);
// [4]把转换单位之后的数据显示到textview上
tv_total_size.setText("总大小:" + totalSpaceSize);
tv_useable_size.setText("可用:" + usableSpaceSize);
}
}</h2>