建立項目
android清單檔案
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.itheima28.memorydemo"
android:versioncode="1"
android:versionname="1.0" >
<uses-sdk
android:minsdkversion="8"
android:targetsdkversion="19" />
<application
android:allowbackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/apptheme" >
<activity
android:name="com.itheima28.memorydemo.mainactivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.main" />
<category android:name="android.intent.category.launcher" />
</intent-filter>
</activity>
</application>
</manifest>
布局檔案
<relativelayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingbottom="@dimen/activity_vertical_margin"
android:paddingleft="@dimen/activity_horizontal_margin"
android:paddingright="@dimen/activity_horizontal_margin"
android:paddingtop="@dimen/activity_vertical_margin"
tools:context="com.itheima28.memorydemo.mainactivity$placeholderfragment" >
<textview
android:id="@+id/tv_memory_info"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerinparent="true"/>
</relativelayout>
查詢記憶體的代碼
package com.itheima28.memorydemo;
import java.io.file;
import android.os.bundle;
import android.os.environment;
import android.os.statfs;
import android.support.v7.app.actionbaractivity;
import android.text.format.formatter;
import android.widget.textview;
public class mainactivity extends actionbaractivity {
@override
protected void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
setcontentview(r.layout.activity_main);
textview tvmemoryinfo = (textview) findviewbyid(r.id.tv_memory_info);
//獲得sd卡的記憶體狀态
file sdcardfiledir = environment.getexternalstoragedirectory();
string sdcardmemory = getmemoryinfo(sdcardfiledir);
//獲得手機内部存儲控件的狀态
file datafiledir = environment.getdatadirectory();
string datamemory = getmemoryinfo(datafiledir);
tvmemoryinfo.settext("sd卡: " + sdcardmemory + "\n手機内部: " + datamemory);
}
/**
* 根據路徑擷取記憶體狀态
* @param path
* @return
*/
@suppresswarnings("deprecation")
private string getmemoryinfo(file path) {
//獲得一個磁盤狀态對象
statfs stat = new statfs(path.getpath());
//獲得一個扇區的大小
long blocksize = stat.getblocksize();
//獲得扇區的總數
long totalblocks = stat.getblockcount();
//獲得可用的扇區數量
long availableblocks = stat.getavailableblocks();
//總空間
string totalmemory = formatter.formatfilesize(this, totalblocks * blocksize);
//可用空間
string availablememory = formatter.formatfilesize(this, availableblocks * blocksize);
return "總空間:" + totalmemory + "\n可用空間:" + availablememory;
}