获取SD卡剩余容量

package com.melody_sd;

import java.io.File;

import android.app.Activity;
import android.os.Build;
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 {
	private TextView tv;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		//获取SD卡路径
		File path = Environment.getExternalStorageDirectory();
		//获取外部存储空间的所有信息
		StatFs stat = new StatFs(path.getPath());
		long blockSize;
		long totalBlocks;
		long availableBlocks;
		blockSize = stat.getBlockSize();			//获取空间块大小
		totalBlocks = stat.getBlockCount();	//获取空间块数量
		availableBlocks = stat.getAvailableBlocks();  //获取可用空间
		
	/*	//判断当前SDK版本是否是4.3或以上   4.3以上支持新方法
		if(Build.VERSION.SDK_INT >= 18){
			blockSize = stat.getBlockSizeLong();			//获取空间块大小
			totalBlocks = stat.getBlockCountLong();	//获取空间块数量
			availableBlocks = stat.getAvailableBlocksLong();  //获取可用空间
		}else{
			blockSize = stat.getBlockSize();			//获取空间块大小
			totalBlocks = stat.getBlockCount();	//获取空间块数量
			availableBlocks = stat.getAvailableBlocks();  //获取可用空间
		}*/
		
		//获取SD卡剩余空间大小   formatter是格式化数据显示类型
		String text = formatSize(availableBlocks * blockSize);
		//显示容量
		tv = (TextView) findViewById(R.id.tv);
		tv.setText(text);
	}

	private String formatSize(long size) {
		return Formatter.formatFileSize(this, size);
	}
}

你可能感兴趣的:(获取SD卡剩余容量)