Android Storage Summary

Source: Internet
Author: User
Tags disk usage

Transferred from: Http://www.liaohuqiu.net/cn/posts/storage-in-android/

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.

    1. Starting with API 19/andorid 4.4/kitkat, you no longer need to explicitly declare these two permissions unless you want to read and write application data from other apps ( $appDataDir )

    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

Basic operations
  1. To use external storage, the required permissions are in AndoridManifest.xml :

     <uses-permission android:name= "android.permission.WRITE_ External_storage "/><uses-permission android:name=" Android.permission.READ_EXTERNAL_STORAGE "/> 

      • 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) |       +-Cache-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)        +- cache        -> Context.getExternalCacheDir()        |        +- ???
    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():         /dataEnvironment.getExternalStorageDirectory():         /storage/sdcard0
        1. Application 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, will be deleted by the system, we should put the app's data in both directories.

        2. 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// 同 $rootDirEnvironment.getExternalStoragePublicDirectory(""):     /storage/sdcard0Environment.getExternalStoragePublicDirectory("folder1"):     /storage/sdcard0/folder1

          Directory under the Application Data directory

          typically 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/cacheContext.getExternalCacheDir():         /storage/sdcard0/Android/data/com.srain.cube.sample/cache
            2. File directory $filesDir = $appDataDir/files :

              • Internal storage: by Context.getFilesDir() getting

                Context.getFileStreamPath(String name)Returns the name file object as a filename, which is name empty, and returns $filesDir itself

                Example:

                Context.getFilesDir():         /data/data/com.srain.cube.sample/files



            1. Related code:

              Https://github.com/liaohuqiu/cube-sdk/blob/master/core/src/com/srain/cube/file/FileUtil.java

     

Android Storage Summary

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.