package xidian.dy.com.chujia; import android.os.Build; import android.os.Environment; import android.os.StatFs; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.format.Formatter; import android.widget.TextView; import java.io.File; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ TextView tv1 = (TextView)findViewById(R.id.total); TextView tv2 = (TextView)findViewById(R.id.available); File f = Environment.getExternalStorageDirectory(); StatFs stat = new StatFs(f.getPath()); long blockSize,totalBlocks,availableBlocks; if(Build.VERSION.SDK_INT >=Build.VERSION_CODES.JELLY_BEAN_MR2){ blockSize = stat.getBlockSizeLong(); totalBlocks = stat.getBlockCountLong(); availableBlocks = stat.getAvailableBlocksLong(); }else { blockSize = stat.getBlockSize(); totalBlocks = stat.getBlockCount(); availableBlocks = stat.getAvailableBlocks(); } if(tv1 != null) tv1.setText("总大小:"+formatSize(blockSize*totalBlocks)); if(tv2 != null) tv2.setText("剩余容量:"+formatSize(blockSize*availableBlocks)); } } private String formatSize(long size){ return Formatter.formatFileSize(this, size); } }
时间: 2024-10-09 12:50:01