activity_main.xml
<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" tools:context=".MainActivity" > <Button android:id="@+id/bt" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="获取容量"/> <TextView android:layout_marginTop="20dp" android:layout_below="@id/bt" android:textSize="20sp" android:id="@+id/tv" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/hello_world" /> </RelativeLayout>
MainActivity.java
package com.example.sdcard; 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.view.View; import android.view.View.OnClickListener; import android.widget.TextView; public class MainActivity extends Activity implements OnClickListener{ private TextView tv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv = (TextView) findViewById(R.id.tv); findViewById(R.id.bt).setOnClickListener(this); } @Override public void onClick(View v) { File file=Environment.getExternalStorageDirectory(); //sdcard的描述 StatFs fs=new StatFs(file.getAbsolutePath()); int blockCount=fs.getBlockCount(); long blockSize=fs.getBlockSize(); int availableBlocks=fs.getAvailableBlocks(); //总容量 long sdcardsize=blockSize*blockCount; //格式化 String sdcardsizeStr=Formatter.formatFileSize(this, sdcardsize); tv.setText("sdcard的总容量:"+sdcardsizeStr); } }