|
我们进来说一下,在android手机里怎么样获取SD卡和手机内存储存空间,有了这个我们会分方便的知道,我们现在手机存储的情况,那么也就不多说什么了,我们还是用代码比较直接,下面重要的地方我都用了注释,希望这个对大家有一些帮助。
java代码: 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.util.Log;
public class Memory extends Activity {
public static final String TAG = "Memory";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
updateMemoryStatus();
}
private void updateMemoryStatus() {
String status = Environment.getExternalStorageState();
String readOnly = "";
// 是否只读
if (status.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
status = Environment.MEDIA_MOUNTED;
readOnly = getString(R.string.read_only);
}
if (status.equals(Environment.MEDIA_MOUNTED)) {
try {
File path = Environment.getExternalStorageDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long totalBlocks = stat.getBlockCount();
long availableBlocks = stat.getAvailableBlocks();
// SD卡总容量
String sdSize = formatSize(totalBlocks * blockSize);
Log.i(TAG, "SD卡总容量: " + sdSize);
// SD卡剩余容量
String sdAvail = formatSize(availableBlocks * blockSize)
+ readOnly;
Log.i(TAG, "SD卡剩余容量: " + sdAvail);
} catch (IllegalArgumentException e) {
status = Environment.MEDIA_REMOVED;
}
}
File path = Environment.getDataDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long availableBlocks = stat.getAvailableBlocks();
// 手机内存剩余容量
String memoryAvail = formatSize(availableBlocks * blockSize);
Log.i(TAG, "手机内存剩余容量: " + memoryAvail);
long totalBlocks = stat.getBlockCount();
// 手机内存总容量
String memorySize = formatSize(totalBlocks * blockSize);
Log.i(TAG, "手机内存总容量: " + memorySize);
}
// 格式化 转化为.MB格式
private String formatSize(long size) {
return Formatter.formatFileSize(this, size);
}
} |
|