Android method to get the SD card path and SDCard memory

  • 2020-06-15 10:09:49
  • OfStack

This article describes the Android method to get the SD card path and SDCard memory. Share to everybody for everybody reference. The specific analysis is as follows:

Yesterday, after studying the problem of the storage path broken through after taking photos, the storage path began to be written dead as: private String folder = "/sdcard/DCIM/Camera/" (the image storage path of SD card camera program); It turns out that although 1 doesn't make any mistakes, it's not very good, because different cameras may cause problems with the path. A better way is to get the path through Environment. Finally, give me an example of how to get the memory of SDCard. The content is as follows:

0. Get the path of sd card.
1. Describe the Environment class.
2. Describe the StatFs class.
3. Complete example to read SDCard memory

0. Get the path of sd card

Method 1:

private String folder = "/sdcard/DCIM/Camera/" ( SD Image storage path of the camera program on the card) ; // Write dead absolute path, do not approve of use 

Method 2:

public String getSDPath(){ 
       File sdDir = null;
       boolean sdCardExist = Environment.getExternalStorageState()  
       .equals(android.os.Environment.MEDIA_MOUNTED);// judge sd Whether the card exists
       if(sdCardExist)  
       {                              
         sdDir = Environment.getExternalStorageDirectory();// Get trace directory
      }  
       return sdDir.toString();
}

Then: Follow by a slash, followed by a file name

String fileName = getSDPath() +"/" + name;// In order to name Stored in the directory 

1. Describe the Environment class

Environment is a class that provides access to environment variables.
Environment contains constants:

MEDIA_BAD_REMOVAL
Explanation: Returns getExternalStorageState() to indicate that SDCard was removed before it was uninstalled
MEDIA_CHECKING
Explanation: Returns getExternalStorageState(), indicating that the object is being checked on disk.
MEDIA_MOUNTED
Explanation: Returns getExternalStorageState(), indicating whether the object exists and has read/write permissions
MEDIA_MOUNTED_READ_ONLY
Explanation: Returns getExternalStorageState(), indicating that object permissions are read-only
MEDIA_NOFS
Explanation: Returns getExternalStorageState(), indicating that the object is blank or using an unsupported file system.
MEDIA_REMOVED
Explanation: returns getExternalStorageState(), if no SDCard exists
MEDIA_SHARED
Explanation: returns getExternalStorageState() if SDCard is not installed and via USB mass storage share
MEDIA_UNMOUNTABLE
Explanation: Return getExternalStorageState(), return SDCard cannot be installed if SDCard exists but cannot be installed
MEDIA_UNMOUNTED
Explanation: Return getExternalStorageState(), return SDCard uninstalled if SDCard is present but not installed

Common methods of Environment:

Methods: getDataDirectory ()
Explanation: Return File for the Android data directory.
Methods: getDownloadCacheDirectory ()
Explanation: Return File for the Android download/cache content directory.
Methods: getExternalStorageDirectory ()
Explanation: Return File to get the external storage directory, SDCard
Methods: getExternalStoragePublicDirectory(String type)
Explanation: Back to File, take a high level common external storage directory to put some types of files in
Methods: getExternalStorageState ()
Explanation: Returns File for the current state of the external storage device
Methods: getRootDirectory ()
Explanation: Return File for the root directory of Android
2. Describe the StatFs class
StatFs 1 class emulates linux's df command to get SD card and phone memory usage
StatFs Common methods:

getAvailableBlocks()
Explanation: Returns Int for the currently available storage space
getBlockCount()
Explanation: Returns Int for the number of file systems available in this area
getBlockSize()
Explanation: Returns Int, size in bytes, 1 file system
getFreeBlocks()
Explanation: Returns Int, the remaining space in the block
restat(String path)
Explanation: Executes a file system referenced by the object
3. Complete example to read SDCard memory
The memory card can be plugged and unplugged at any time on the Android mobile phone. Each action will cause ACTION_BROADCAST to the operating system. This example will use the method learned above to calculate the remaining capacity and total capacity of SDCard. The code is as follows:

package com.terry;
import java.io.File; 
import java.text.DecimalFormat; import android.R.integer;
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;
import android.widget.Toast;
public class getStorageActivity extends Activity {
private Button myButton;
/** Called when the activity is first created. */
@Override
public
void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       findView();
       viewHolder.myButton.setOnClickListener(new OnClickListener() {
         @Override
         public
void onClick(View arg0) {
            // TODO Auto-generated method stub
            getSize();
         }
       });
}
void findView(){
       viewHolder.myButton=(Button)findViewById(R.id.Button01);
       viewHolder.myBar=(ProgressBar)findViewById(R.id.myProgressBar);
       viewHolder.myTextView=(TextView)findViewById(R.id.myTextView);
}
void getSize(){
       viewHolder.myTextView.setText("");
       viewHolder.myBar.setProgress(0);
      // Determine if there is an insert memory card
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
         File path =Environment.getExternalStorageDirectory();
         // achieve sdcard The file path
         StatFs statfs=new StatFs(path.getPath());
         // To obtain block the SIZE
long blocSize=statfs.getBlockSize();
         // To obtain BLOCK The number of
long totalBlocks=statfs.getBlockCount();
         // F the use of Block The number of
long availaBlock=statfs.getAvailableBlocks();
         String[] total=filesize(totalBlocks*blocSize);
         String[] availale=filesize(availaBlock*blocSize);
         // Sets the maximum value of the progress bar
int maxValue=Integer.parseInt(availale[0])
         *viewHolder.myBar.getMax()/Integer.parseInt(total[0]);
         viewHolder.myBar.setProgress(maxValue);
         String Text=" A total of: "+total[0]+total[1]+"/n"
+" available :"+availale[0]+availale[1];
         viewHolder.myTextView.setText(Text);
       }else
if(Environment.getExternalStorageState().equals(Environment.MEDIA_REMOVED)){
         Toast.makeText(getStorageActivity.this, " There is no sdCard",1000).show();
       }
}
// Returns an array, subscript 1 It's the magnitude, the subscript 2 On behalf of the unit KB/MB
String[] filesize(long size){
       String str="";
      if(size>=1024){
         str="KB";
         size/=1024;
         if(size>=1024){
            str="MB";
            size/=1024;
         }
       }
       DecimalFormat formatter=new DecimalFormat();
       formatter.setGroupingSize(3);
       String result[] =new String[2];
       result[0]=formatter.format(size);
       result[1]=str;
      return result;
}
}

I hope this article has been helpful for your Android programming.


Related articles: