今天我們準(zhǔn)備學(xué)習(xí)下圖的sd卡空間讀取的方法

其他的話不贅述,直奔主題。看下面的分解步驟:
1、首先創(chuàng)建一個(gè)工程:

之后一路下一步,創(chuàng)建好工程
2、來到“sd卡的大小\res\layout\activity_main.xml”文件下,創(chuàng)建兩個(gè)textview:
<TextView
android:id="@+id/textview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="總大小"/>
<TextView
android:id="@+id/textview2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="65dp"
android:text="可用空間"/>
3、來到MainActivity下,開始獲取sd卡空間大小:
protected ?void ?onCreate(BundlesavedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextViewtextview1= (TextView) findViewById(R.id.textview1);
TextViewtextview2= (TextView) findViewById(R.id.textview2);
// 獲取sd卡總大小和可用空間
Filefile= Environment.getExternalStorageDirectory();
longtotalSpace=file.getTotalSpace();
longuseableSpace=file.getUsableSpace();
// 對(duì)sd卡大小進(jìn)行轉(zhuǎn)換數(shù)據(jù)格式
StringftotalSpace= Formatter.formatFileSize(this,totalSpace);
StringfuseableSpace= Formatter
.formatFileSize(this,useableSpace);
// 展示到textview上
textview1.setText("總大?。?+ftotalSpace);
textview2.setText("剩余空間:"+fuseableSpace);
}
4、通常在上面的代碼編寫后程序會(huì)報(bào)錯(cuò),如下圖:

這個(gè)是API版本的問題,更改一下版本即可。在AndroidManifest.xml里面,將
<uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="21"/>里面的android:minSdkVersion的值改成9就可以了。
好了,關(guān)于如何獲取sd卡空間大小到這里已經(jīng)差不多結(jié)束了。大家一定要記得對(duì)sd卡的大小進(jìn)行格式化轉(zhuǎn)換,否則用戶的對(duì)于用戶的感受度和使用合理性都非常不好。