獲取手機存儲設備的空間使用情況

Android系統提供了Environment 和StatFs兩個類,配合可以實現對存儲設備容量的查看。

  Environment: 獲取系統中的存儲設備信息


    getDataDirectory(): 獲取應用存儲空間文件對象。
    getExternalStorageDirectory(): 獲取外部存儲設備及SD卡文件對象。

    getRootDirectory(): 獲取系統空間文件對象。


  StatFs: 用於獲取具體文件的信息。
    getBlockCount(): 獲取存儲塊數量。
    getAvailableBlocks(): 獲取存儲塊數量。
    getBlockSize(): 獲取存儲塊大小。

  因爲Android是基於Linux系統的,所以其沒有盤符的概念,而且是以存儲塊來存儲數據。所以獲得容量的正確方式爲:
  1. 通過Environment獲取需要檢測容量的文件對象。
  2. 構建StatFs對象。
  3. 獲取存儲塊數量。
  4. 獲取存儲塊大小。
  5. 計算得出容量大小。

  通過getBlockSize()方法獲取出來的值,是以字節做單位。


下面是代碼:

package Getystem_file_info.demo;


import java.io.File;
import java.text.DecimalFormat;


import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.view.View;
import android.widget.TextView;


public class MainActivity extends Activity {
private TextView tv1,tv2,tv3,tv4;


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findVeiw();

if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
File externalStoragePath = Environment.getExternalStorageDirectory();

StatFs statFs = new StatFs(externalStoragePath.getPath());

int blockSize = statFs.getBlockSize();

int blockCount = statFs.getBlockCount();

int availableBlocks = statFs.getAvailableBlocks();

int freeBlocks = statFs.getFreeBlocks();


String[] blockSizes = sizeFormat(blockCount*blockSize);
String[] availableSize = sizeFormat(availableBlocks*blockSize);
String[] freebleSize = sizeFormat(freeBlocks*blockSize);

tv1.setText("外儲設備總大小:"+ blockSizes[0] + blockSizes[1] );
tv2.setText("外儲設備可用大小:"+ availableSize[0] + availableSize[1] );
tv3.setText("外儲設備freeBlocks大小:"+ freebleSize[0] + freebleSize[1] );


}

}


private void findVeiw() {
tv1 = (TextView) this.findViewById(R.id.textview1);
tv2 = (TextView) this.findViewById(R.id.textview2);
tv3 = (TextView) this.findViewById(R.id.textview3);
}


String[] sizeFormat(long size) {
String str = "B";
if(size >= 1024) {
str = "KB";
size /= 1024;
if(size >= 1024) {
str = "MB";
size /= 1024;
}
}

DecimalFormat format = new DecimalFormat();
format.setGroupingSize(3);
String[] result = new String[2];

result[0] = format.format(size);
result[1] = str;

return result;
}
}