Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android學習筆記之——獲取SD卡及手機ROM容量

android學習筆記之——獲取SD卡及手機ROM容量

編輯:關於Android編程

繼續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部分的源碼,來加深了解。



  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved