本文實例講述了Android檢測手機中存儲卡及剩余空間大小的方法。分享給大家供大家參考,具體如下:
Android中Environment可用來檢測手機中是否安裝有存儲卡以及文件存儲路徑等。StatFs可以獲取存儲卡的空間大小以及剩余空間大小。DecimalFormat可以實現把數字劃分為一定的格式。
具體程序如下:
import java.io.File;import java.text.DecimalFormat;import android.app.Activity;import android.os.Bundle;import android.os.Environment;import android.os.StatFs;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.ProgressBar;import android.widget.TextView;public class A08Activity extends Activity { private TextView tv;//用來顯示存儲卡的情況 private Button b;//觸發檢測存儲卡事件 private ProgressBar pb;//用ProgressBar來顯示存儲卡的狀況 /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); tv=(TextView)findViewById(R.id.tv); b=(Button)findViewById(R.id.button); pb=(ProgressBar)findViewById(R.id.pb); b.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { // TODO Auto-generated method stub showSize();//用來檢測存儲卡的存儲情況 } }); } protected void showSize() { // TODO Auto-generated method stub tv.setText(""); pb.setProgress(0); //用來檢測存儲卡是否存在 if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ //如果存儲卡存在,則獲取存儲文件的路徑 File path=Environment.getExternalStorageDirectory(); StatFs sf=new StatFs(path.getPath());//創建StatFs對象 long blockSize=sf.getBlockSize();//獲得blockSize long totalBlock=sf.getBlockCount();//獲得全部block long availableBlock=sf.getAvailableBlocks();//獲取可用的block //用String數組來存放Block信息 String[] total=fileSize(totalBlock*blockSize); String[] available=fileSize(availableBlock*blockSize); //在ProgressBar中顯示可用空間的大小 int a=Integer.parseInt(available[0]); pb.setProgress(a); String s="SD卡中空間總共有:"+total[0]+total[1]+"/n"; s+="剩余空間大小:"+available[0]+available[1]; tv.setText(s); } else if(Environment.getExternalStorageState().equals(Environment.MEDIA_REMOVED)){ tv.setText("SD卡已移除"); } } //用來定義存儲空間顯示格式 public String[] fileSize(long size){ String s=""; if(size>1024){ s="KB"; size/=1024; if(size>1024){ s="MB"; size/=1024; } } DecimalFormat df=new DecimalFormat(); df.setGroupingSize(3); String[] result=new String[3]; result[0]=df.format(size); result[1]=s; return result; }}
更多關于Android相關內容感興趣的讀者可查看本站專題:《Android控件用法總結》及《Android開發入門與進階教程》
希望本文所述對大家Android程序設計有所幫助。
新聞熱點
疑難解答
圖片精選