Android file storage use reference

Source: Internet
Author: User
Tags disk usage

problems that you may encounter

The Android system itself has its own storage, and the SD card can be used to expand the storage space. The former is like the hard disk in PC, the latter is good to move hard. The former space is small, the latter space is large, but the latter is not necessarily available. These issues may be encountered when developing applications that handle local data access:

    1. Need to determine whether the SD card is available: Occupy too much internal storage of the fuselage, easy to incur user antipathy, priority to store data in the SD card;
    2. Application data storage path, should be consistent with other apps, erase data when the app unloads:

      • Unconventional in the SD card root directory to create a directory, causing users to resent
      • Users are disgusted with residual directories or data on the user's machine after uninstalling the application
    3. Need to judge the free space between the two: when the SD card exists, the available space is smaller than the internal storage of the fuselage, then the body storage should be selected;

    4. Data security, the application data is not willing to be read and written by other applications;
    5. Image cache, etc., should not be scanned into the user album and other Media library.
Basic Operations
  1. Use external storage, required permissions, in  andoridmanifest.xml  :

      << Span class= "title" >uses-permission android:name= " Android.permission.WRITE_EXTERNAL_STORAGE "/><uses-permission android:name= "Android.permission.READ_EXTERNAL_STORAGE"/>           

     )

  2. To determine the SD card available:

    /** * Check if the primary "external" storage device is available. *  * @return */public static boolean hasSDCardMounted() { String state = Environment.getExternalStorageState(); if (state != null && state.equals(Environment.MEDIA_MOUNTED)) { return true; } else { return false; }}
Usage of storage
  • Depending on the system user, the amount of storage space that can be occupied varies

    At API Level 9 and above, File the object's getFreeSpace() method obtains the system root user free space;

    getUsableSpace()Take non-root user free space

  • Get disk usage When multiple stores are available, and choose the right storage based on current system conditions.

  • According to the system storage usage, reasonably set the size of the space used by the app, and can also do dynamic adjustment when running.

  • In the API level 9 and above the system, you can directly invoke File the relevant methods of the object, the following self-calculation:

      @TargetApi (version_codes. Gingerbread) public static long getusablespace ( File path) {if (path = = null) {return-1; } if (Build.VERSION.SDK_INT >= build.version_codes. Gingerbread) {return path.getusablespace ();} else {if (!path.exists ()) {return 0; } else {final StatFs stats = new StatFs ( Path.getpath ()); return (long) stats.getblocksize () * (long) Stats.getavailableblocks (); } }} 
the law of the path

Generally, the Context path to Environment file access is obtained through and related methods.

With these two classes, you get a variety of paths,

($rootDir) +-/data, environment.getdatadirectory () |   ||   |   ($appDataDir) |       +-data/com.srain.cube.sample|       ||   | ($filesDir) | + + files, Context.getfilesdir ()/Context.getfilestreampath ("")| | || | +-File1-Context.getfilestreampath ("File1") | | ($cacheDir) | +-Context.getcachedir () | | | + App_$name (Context.getdir (String name, int mode) | | ($rootDir) +- /storage/sdcard0-environment.getexternalstoragedirectory () | /Environment.getexternalstoragepublicdirectory ("") | +-Dir1-environment.getexternalstoragepublicdirectory ("Dir1") | | ($appDataDir) +-andorid/data/com.srain.cube.sample | | ($filesDir) +-Context.getexternalfilesdir ("") | | | +-File1-Context.getexternalfilesdir ("File1") | +-Music--Context.getexternalfilesdir (environment.music); | +-picture--... Environment.picture | +- ... | | ($cacheDir) +-Context.getexternalcachedir ()-cache | +- ???
characteristics of each path

The following describes the characteristics of these paths and the details to be aware of in use:

  1. root directory ( $rootDir ):
    • Internal storage path: /data , by Environment.getDataDirectory() getting
    • External storage path: /storage/sdcard0 (also similar to/mnt/), by Environment.getExternalStorageDirectory() obtaining

      Example:

        Environment.getDataDirectory():           /data  Environment.getExternalStorageDirectory():           /storage/sdcard0
  2. app Data Catalog (  $appDataDir  )
    • Internal storage:    $appDataDir = $rootDir/data/$packageName  ,
    • External storage:    $appDataDir = $rootDir/andorid/data/$packageName

    The data in these directories, after the app is uninstalled, is deleted by the system, and we should put the applied data in both directories.

  3. The data directory that is exposed in external storage. These directories will not be deleted by the system as the app is deleted, please use:

     Environment.getExternalStorageDirectory():      /storage/sdcard0 // 同 $rootDir Environment.getExternalStoragePublicDirectory(""):      /storage/sdcard0 Environment.getExternalStoragePublicDirectory("folder1"): /storage/sdcard0/folder1
  4. Directory under the Application Data directory

    in general, under $appdatadir, there will be two directories :

    1. Data cache: $cacheDir = $appDataDir/cache :
      • Internal storage: Context.getCacheDir() When the body is out of memory, the file is deleted
      • External storage:Context.getExternalCacheDir()

        External storage without real-time monitoring, when the space is low, the file will not be deleted in real time, may return an empty object

        Example:

          Context.getCacheDir():           /data/data/com.srain.cube.sample/cache  Context.getExternalCacheDir():           /storage/sdcard0/Android/data/com.srain.cube.sample/cache
    2. File directory$filesDir = $appDataDir/files:
      • Internal storage: Via  context.getfilesdir ()    get

        context.getfilestreampath (String name)   return to   name   file object for file name,  name   is empty, returns    $filesDir    itself

        Example:

         Context.getfilesdir (): /data/data/co M.srain.cube.sample/files Context.getfilestreampath (/data/data/co M.srain.cube.sample/files Context.getfilestreampath ( "File1"): /data/da Ta/com.srain.cube.sample/files/file1       
      • External storage: Passed Context.getExternalFilesDir(String type) as type an empty string when fetched.

        typeThe system specifies several types:

          Environment.DIRECTORY_MUSIC  Environment.DIRECTORY_PICTURES  ...

        Example:

          Context.getExternalCacheDirs():           /storage/sdcard0/Android/data/com.srain.cube.sample/files  Context.getExternalFilesDir(Environment.DIRECTORY_MUSIC)          /storage/sdcard0/Android/data/com.srain.cube.sample/files/Music
    3. $cacheDir/$filesDir    security

      In internal storage,   $cacheDir  ,   $filesDir   is app-safe, Other apps cannot read data from this app, while external storage is not.

      In external storage, these two folders are also accessible to other applications.

      in external storage, media files in the   $filesDir   are not scanned as media and added to the Media Library.

    4. $cacheDir / $filesDirSibling directory

      In internal storage: through Context.getDir(String name, int mode) the available and $filesDir /or $cacheDir sibling directories

      The directory is named app_ + name by the mode to control whether the directory is for app private or other apps to read and write.

      Example:

      Context.getDir("dir1", MODE_PRIVATE):        Context.getDir: /data/data/com.srain.cube.sample/app_dir1
    5. In particular, for external storage, get $cacheDir or $filesDir and the path below

      Under API Level 8, or if there is not enough space, the associated method will need to be constructed when the path is empty.

      @TargetApi (version_codes. FROYO)PublicStatic File Getexternalcachedir (context context) {     if (Build.VERSION.SDK_INT >= build.version_codes. FROYO)) {File path = Context.getexternalcachedir (); //In some case, even the SD card is mounted, //Getexternalcachedir would return null //May be it is nearly f Ull. if (path! = null) { return path;}} //Before Froyo or the path is NULL, //We need to construct the external cache folder ourselves final String Cachedir = "/android/data/" + context.getpackagename () + "/cache/"; return New File (Environment.getexternalstoragedirectory (). GetPath () + Cachedir);}     

Android file storage use reference

Related Article

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.