android学习笔记之——获取SD卡及手机ROM容量

          继续android学习之旅,今天通过一个小例子,来获取SD卡的容量和手机ROM的容量,具体代码如下:

package com.urovo.sdcardspace;

import java.io.File;

import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.app.Activity;
import android.text.format.Formatter;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		TextView tv = (TextView) findViewById(R.id.tv);
		
		File path = Environment.getExternalStorageDirectory();//得到SD卡的路径
	    StatFs stat = new StatFs(path.getPath());//创建StatFs对象,用来获取文件系统的状态
	    long blockCount = stat.getBlockCount();
	    long blockSize = stat.getBlockSize();
	    long availableBlocks = stat.getAvailableBlocks();
	    
	    String totalSize = Formatter.formatFileSize(getApplicationContext(), blockCount*blockSize);//格式化获得SD卡总容量
	    String availableSize = Formatter.formatFileSize(getApplicationContext(), blockCount*availableBlocks);//获得SD卡可用容量
	    
	    tv.setText("SD卡总容量:"+totalSize+"\nSD卡可用容量:"+availableSize+"\n"+getRomSpace());
	}

	private String getRomSpace() {
		File path = Environment.getDataDirectory();
	    StatFs stat = new StatFs(path.getPath());
	    long blockCount = stat.getBlockCount();
	    long blockSize = stat.getBlockSize();
	    long availableBlocks = stat.getAvailableBlocks();
	    
	    String totalSize = Formatter.formatFileSize(getApplicationContext(), blockCount*blockSize);
	    String availableSize = Formatter.formatFileSize(getApplicationContext(), blockCount*availableBlocks);
	    
		return "手机Rom总容量:"+totalSize+"\n手机Rom可用容量:"+availableSize;
	}

}

具体的内容,可以通过分析android settings部分的源码,来加深了解。

 
  

你可能感兴趣的:(Android)