Android uses mount to get SD card directory and how to obtain SD card memory

Source: Internet
Author: User

The

Android system is a Linux system, and we can use the Linux command Mouunt to get a Linux mount directory. The directory that the

obtains from the command I did not traverse, and if you still cannot get it, you can iterate through all the directories that the mount has been to.


File  sdcard ;
@SuppressLint("SdCardPath")
    public File getSdCardFile() {
        if (sdcard != null) {
            return sdcard;
        }
        List<String> list = getExtSDCardPath();
        boolean isRun = true;
        if (list.size() > 0) {
            sdcard = new File(list.get(list.size() - 1));
            if (sdcard.isDirectory()) {
                if (sdcard.getFreeSpace() == 0) {
                    isRun = true;
                } else {
                    isRun = false;
                }
            }
        }
        if (isRun) {
            sdcard = Environment.getExternalStorageDirectory();
            if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                sdcard = new File("/sdcard/");
                log.e("sdcard  spance:" + sdcard.getFreeSpace());
                if (sdcard.getFreeSpace() == 0) {
                    sdcard = new File("/sdcard1/");
                    log.e("sdcard1 space:" + sdcard.getFreeSpace());
                }
                if (sdcard.getFreeSpace() == 0) {
                    sdcard = new File("/sdcard2/");
                    log.e("sdcard2 space:" + sdcard.getFreeSpace());
                }
            }
        }
        log.e("data:" + sdcard.getAbsolutePath());
        return sdcard;
    }
    public List<String> getExtSDCardPath() {
        List<String> lResult = new ArrayList<String>();
        try {
            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec("mount");
            InputStream is = proc.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line;
            while ((line = br.readLine()) != null) {
                if (line.contains("extSdCard")) {
                    String[] arr = line.split(" ");
                    String path = arr[1];
                    if (path.lastIndexOf("extSdCard") == path.length() - 9) {
                        File file = new File(path);
                        if (file.isDirectory()) {
                            lResult.add(path);
                        }
                    }
                } else if (line.contains("/sdcard")) {
                    String[] arr = line.split(" ");
                    String path = arr[1];
                    if (path.lastIndexOf("/sdcard") == path.length() - 6) {
                        File file = new File(path);
                        if (file.isDirectory()) {
                            lResult.add(path);
                        }
                    } else {
                        String number = path.substring(path.lastIndexOf("/sdcard") + 7);
                        try {
                            Integer.parseInt(number);
                            File file = new File(path);
                            if (file.isDirectory()) {
                                lResult.add(path);
                            }
                        } catch (Exception e) {
                        }
                    }
                }
            }
            isr.close();
        } catch (Exception e) {
        }
        return lResult;
    }



However, the preferred storage is to use the method provided by Android first to judge and obtain the SDcard directory.


Determine if sdcard exists
environment.getexternalstoragestate (). Equals (environment.media_mounted);
If present, get the storage file directory
environment.getexternalstoragedirectory ();




Android SD card Path problem and how to get sdcard memory

After studying the problem of the storage path breakthrough after taking a photo, start the storage path to write dead: private String folder = "/sdcard/dcim/camera/" (Image storage path on SD card photo program); Later found that this writing although generally not wrong, but not very good, because different cameras, possible path problems. A better approach is to get the path through environment, and finally give an example of how to get the sdcard memory and show it to the user. The content of the story is as follows:
0, get the SD card path.
1, tell the Environment class.
2, tell the Statfs class.
3. Full example read SDcard memory

0. Get SD card Path
Method One: Private String folder = "/sdcard/dcim/camera/" (Image storage path of the photo program on SD card); Write dead absolute path, not in favor of using

Method Two:


public String getSDPath () {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState ()
                            .equals (Android.os.Environment.MEDIA_MOUNTED); // Determine if the SD card
        if (sdCardExist)
        {
          sdDir = Environment.getExternalStorageDirectory (); // Get the directory
       }
        return sdDir.toString ();
      
}


Then: With a slash in the back, plus a filename
String fileName = Getsdpath () + "/" + name;//exists in directory with name


1, tell the Environment class
Environment is a class that provides access to environment variables.
Environment contains constants:
Media_bad_removal
Explanation: Returns Getexternalstoragestate () indicating that the sdcard was removed before being unloaded
Media_checking
Explanation: Returns Getexternalstoragestate () to indicate that the object is checking for disk.
media_mounted
Explanation: Returns Getexternalstoragestate () indicating whether the object exists and has read/write permissions
Media_mounted_read_only
Explanation: Returns Getexternalstoragestate () to indicate that the object permission is read-only
Media_nofs
Explanation: Returns Getexternalstoragestate () that indicates that the object is blank or is using an unsupported file system.
Media_removed
Explanation: Returns Getexternalstoragestate (), if no sdcard returns
Media_shared
Explanation: Return Getexternalstoragestate (), if SDcard not installed, and return via USB bulk storage share
Media_unmountable
Explanation: Return Getexternalstoragestate (), return sdcard cannot be installed if SDcard is present but cannot be installed
media_unmounted
Explanation: Return Getexternalstoragestate (), return SDcard has been unloaded if sdcard is present but not installed
Environment Common methods:
Method: Getdatadirectory ()
Explanation: Return to File to get the Android data directory.
Method: Getdownloadcachedirectory ()
Explanation: Return to File to get the Android download/cache content directory.
Method: getExternalStorageDirectory ()
Explanation: Returns File to get the external storage directory that SDcard
Method: Getexternalstoragepublicdirectory (String type)
Explanation: Returns file, takes a high-end public external memory directory to put some types of files
Method: Getexternalstoragestate ()
Explanation: Returns File to get the current state of the external storage device
Method: Getrootdirectory ()
Explanation: Return to File to get Android's root directory



2, tell the Statfs class
Statfs a class of the DF command that simulates Linux, obtaining the use of SD card and phone memory
Statfs Common methods:
Getavailableblocks ()
Explanation: Returns an Int to get the currently available storage space
Getblockcount ()
Explanation: Returns an Int to get the number of file systems available in the zone
Getblocksize ()
Explanation: Returns INT, size, in bytes, a file system
Getfreeblocks ()
Explanation: Returns an Int, the space remaining in the block area
REStat (String Path)
Explanation: Executes a file system referenced by this object

3. Full example read SDcard memory
The memory card can be plugged in on the Android phone at any time, each action will cause the operating system to Action_broadcast, this example will use the method learned above to calculate the sdcard of the remaining capacity and total capacity. 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 a memory card is inserted
if (Environment.getExternalStorageState (). equals (Environment.MEDIA_MOUNTED)) {
         File path = Environment.getExternalStorageDirectory ();
         // Get sdcard file path
         StatFs statfs = new StatFs (path.getPath ());
         // Get the size of the block
long blocSize = statfs.getBlockSize ();
         // Get the number of BLOCKs
long totalBlocks = statfs.getBlockCount ();
         // Number of blocks used
long availaBlock = statfs.getAvailableBlocks ();
        
         String [] total = filesize (totalBlocks * blocSize);
         String [] availale = filesize (availaBlock * blocSize);
         // Set 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 = "Total:" + 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, "No sdCard", 1000) .show ();
       }
}
// return the array, subscript 1 represents the size, subscript 2 represents 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;
}
} 




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.