Android access to SD card path and SDcard memory method _android

Source: Internet
Author: User

This article illustrates how Android obtains the SD card path and SDcard memory. Share to everyone for your reference. The specific analysis is as follows:

Yesterday in studying the problem of the storage path breakthrough after the photo shoot, the beginning of the storage path is written to death: 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:

Copy Code code as follows:
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:

Copy Code code as follows:
Public String Getsdpath () {
File sddir = null;
Boolean sdcardexist = Environment.getexternalstoragestate ()
. Equals (Android.os.Environment.MEDIA_MOUNTED);//To determine whether the SD card exists
if (sdcardexist)
{
Sddir = Environment.getexternalstoragedirectory ();//Fetch directory
}
return sddir.tostring ();
}

Then: With a slash in the back, plus a filename

Copy Code code as follows:
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:

Copy Code code 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 the activity is a. */
@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 ();
Get sdcard file path
Statfs statfs=new Statfs (Path.getpath ());
Gets the size of the block
Long Blocsize=statfs.getblocksize ();
Get block number
Long Totalblocks=statfs.getblockcount ();
Number of blocks already in use
Long Availablock=statfs.getavailableblocks ();
String[] Total=filesize (totalblocks*blocsize);
String[] Availale=filesize (availablock*blocsize);
Set the maximum of a 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 ();
}
}
Returns 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;
}
}

I hope this article will help you with your Android program.

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.