一、在Manifest.xml文件中,写外部设备写权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
如果是用得模拟器,要确保创建AVD时,已经为SDcard分配了空间。
二、判断SDcard有没有挂载,若没有挂载,则弹提示:
if(!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
Toast.makeText(this, "External SD card not mounted没有挂载", Toast.LENGTH_LONG).show();
}
package com.jiangge.sdcardsize;
import java.io.File;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
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);
TextView textView = (TextView) findViewById(R.id.tv_show);
File path = Environment.getExternalStorageDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long totalBlockCounts = stat.getBlockCount();
long availableBlocks = stat.getAvailableBlocks();
long totalSize = blockSize * totalBlockCounts;
long avaliableSize = availableBlocks * blockSize;
String totalSizeStr = Formatter.formatFileSize(this, totalSize);
String avaliableSizeStr = Formatter.formatFileSize(this, avaliableSize);
textView.setText("总内存:" + totalSizeStr + "\n" + "可用内存:" + avaliableSizeStr);
}
}
小米手机真机调试结果:(可以在手机中,Menu->Settings->SD card and phone storage's number)
StackOverFlow 上一个问答:
StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
double sdAvailSize = (double)stat.getAvailableBlocks()
* (double)stat.getBlockSize();
//One binary gigabyte equals 1,073,741,824 bytes.
double gigaAvailable = sdAvailSize / 1073741824;
getAvailableBlocks()
and getBlockSize()
are bothdeprecated in API 18 so I would do some kind of check on your build version to make sure you are applying the correct methods:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
@SuppressWarnings("deprecation")
long sdAvailSize = (long) stat.getAvailableBlocksLong() * (long) stat.getBlockSizeLong();
} else {
@SuppressWarnings("deprecation")
double sdAvailSize = (double) stat.getAvailableBlocks() * (double) stat.getBlockSize();
}