Android SD卡讀取資訊(StatFs、MediaPlayer)

這次練習的項目主要是取得SD卡的資訊
並利用MediaPlayer讀取在SD上的文件並撥放。
主要在學習操作StatFs這個類別,用途在取得系統中的磁碟資訊
跟C#中的這一篇用途滿相像的







說明:
1.按第一個鍵,取得目前SD卡的資訊
2.按第二個鍵開始撥放,再按一次會停止

參考:
URI與URL的區別
Android MediaPlayer的生命周期

程式碼:

public static class PlaceholderFragment extends Fragment {
 Button btn,play;
 TextView tv;
 MediaPlayer mp;
 boolean musicFlag = true;
 Uri uri = Uri.fromFile(new File("storage/sdcard/guitar.mp3"));
        //取得音樂檔的Uri
 public PlaceholderFragment() {
 }

 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
   Bundle savedInstanceState) {
  View rootView = inflater.inflate(R.layout.fragment_main, container,
    false);
  btn = (Button) rootView.findViewById(R.id.button1);
  play = (Button) rootView.findViewById(R.id.button2);
  tv = (TextView) rootView.findViewById(R.id.textView1);
  //mp = new MediaPlayer();
  
  btn.setOnClickListener(new OnClickListener() {  
   @Override
   public void onClick(View v) {
    if(Environment.getExternalStorageState()
      .equals(Environment.MEDIA_MOUNTED)){
     //判斷是否有插入sd
     File filePath = Environment.getExternalStorageDirectory();
     //取得路徑
     StatFs stat = new StatFs(filePath.getPath());
     //取得statFs物件
     long blockSize = stat.getBlockSizeLong();
     //取得每個Block的Size
     float totalBlock = stat.getBlockCountLong();
     //總共有幾個Block
     int sizeInMb =(int) (blockSize*totalBlock)/1024/1024;
     //相乘後換算成Mb大小
     long availableBlocks =stat.getAvailableBlocksLong();
     //目前可用的Block
     float percent = availableBlocks/totalBlock;
     percent = (int)(percent*1000);
     //將小數點往前位移
     StringBuilder sb = new StringBuilder();
     
     sb.append("SD Card使用情況:\n")
       .append("總容量:").append(sizeInMb+"MB\n")
       .append("已 用:").append((1000-percent)/10.0f+"%\n")
       //將percent換算
       .append("可 用:").append(percent/10.f+"%\n")

       //以下顯示真實數據
       .append("blockSize:" + blockSize+"\n")
       .append("totalBlock:" + totalBlock+"\n")
       .append("availableBlocks:" + availableBlocks+"\n")
       .append("percent:" + percent+"\n");
       
     tv.setText(sb.toString());
    }else{
     Toast.makeText(getActivity(), "未插入SD卡", Toast.LENGTH_SHORT).show();
    }
   }
  });
  
  play.setOnClickListener(new OnClickListener() {
   
   @Override
   public void onClick(View arg0) {
    if(musicFlag){
     try {
      mp = MediaPlayer.create(getActivity(), uri);
      mp.start();
      tv.setText("正在撥放音樂");
      play.setText("Stop");
      musicFlag = false;
     } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    }else{
     mp.stop();
     mp.release();
     play.setText("play");
     musicFlag =true;
    }
   }
  });
  
  return rootView;
 }
}

留言

熱門文章