Home | History | Annotate | Download | only in os
      1 /*
      2  * Copyright (C) 2007 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package android.os;
     18 
     19 import android.app.admin.DevicePolicyManager;
     20 import android.content.Context;
     21 import android.os.storage.StorageManager;
     22 import android.os.storage.StorageVolume;
     23 import android.text.TextUtils;
     24 import android.util.Log;
     25 
     26 import java.io.File;
     27 
     28 /**
     29  * Provides access to environment variables.
     30  */
     31 public class Environment {
     32     private static final String TAG = "Environment";
     33 
     34     private static final String ENV_EXTERNAL_STORAGE = "EXTERNAL_STORAGE";
     35     private static final String ENV_ANDROID_ROOT = "ANDROID_ROOT";
     36     private static final String ENV_ANDROID_DATA = "ANDROID_DATA";
     37     private static final String ENV_ANDROID_EXPAND = "ANDROID_EXPAND";
     38     private static final String ENV_ANDROID_STORAGE = "ANDROID_STORAGE";
     39     private static final String ENV_DOWNLOAD_CACHE = "DOWNLOAD_CACHE";
     40     private static final String ENV_OEM_ROOT = "OEM_ROOT";
     41     private static final String ENV_ODM_ROOT = "ODM_ROOT";
     42     private static final String ENV_VENDOR_ROOT = "VENDOR_ROOT";
     43 
     44     /** {@hide} */
     45     public static final String DIR_ANDROID = "Android";
     46     private static final String DIR_DATA = "data";
     47     private static final String DIR_MEDIA = "media";
     48     private static final String DIR_OBB = "obb";
     49     private static final String DIR_FILES = "files";
     50     private static final String DIR_CACHE = "cache";
     51 
     52     /** {@hide} */
     53     @Deprecated
     54     public static final String DIRECTORY_ANDROID = DIR_ANDROID;
     55 
     56     private static final File DIR_ANDROID_ROOT = getDirectory(ENV_ANDROID_ROOT, "/system");
     57     private static final File DIR_ANDROID_DATA = getDirectory(ENV_ANDROID_DATA, "/data");
     58     private static final File DIR_ANDROID_EXPAND = getDirectory(ENV_ANDROID_EXPAND, "/mnt/expand");
     59     private static final File DIR_ANDROID_STORAGE = getDirectory(ENV_ANDROID_STORAGE, "/storage");
     60     private static final File DIR_DOWNLOAD_CACHE = getDirectory(ENV_DOWNLOAD_CACHE, "/cache");
     61     private static final File DIR_OEM_ROOT = getDirectory(ENV_OEM_ROOT, "/oem");
     62     private static final File DIR_ODM_ROOT = getDirectory(ENV_ODM_ROOT, "/odm");
     63     private static final File DIR_VENDOR_ROOT = getDirectory(ENV_VENDOR_ROOT, "/vendor");
     64 
     65     private static UserEnvironment sCurrentUser;
     66     private static boolean sUserRequired;
     67 
     68     static {
     69         initForCurrentUser();
     70     }
     71 
     72     /** {@hide} */
     73     public static void initForCurrentUser() {
     74         final int userId = UserHandle.myUserId();
     75         sCurrentUser = new UserEnvironment(userId);
     76     }
     77 
     78     /** {@hide} */
     79     public static class UserEnvironment {
     80         private final int mUserId;
     81 
     82         public UserEnvironment(int userId) {
     83             mUserId = userId;
     84         }
     85 
     86         public File[] getExternalDirs() {
     87             final StorageVolume[] volumes = StorageManager.getVolumeList(mUserId,
     88                     StorageManager.FLAG_FOR_WRITE);
     89             final File[] files = new File[volumes.length];
     90             for (int i = 0; i < volumes.length; i++) {
     91                 files[i] = volumes[i].getPathFile();
     92             }
     93             return files;
     94         }
     95 
     96         @Deprecated
     97         public File getExternalStorageDirectory() {
     98             return getExternalDirs()[0];
     99         }
    100 
    101         @Deprecated
    102         public File getExternalStoragePublicDirectory(String type) {
    103             return buildExternalStoragePublicDirs(type)[0];
    104         }
    105 
    106         public File[] buildExternalStoragePublicDirs(String type) {
    107             return buildPaths(getExternalDirs(), type);
    108         }
    109 
    110         public File[] buildExternalStorageAndroidDataDirs() {
    111             return buildPaths(getExternalDirs(), DIR_ANDROID, DIR_DATA);
    112         }
    113 
    114         public File[] buildExternalStorageAndroidObbDirs() {
    115             return buildPaths(getExternalDirs(), DIR_ANDROID, DIR_OBB);
    116         }
    117 
    118         public File[] buildExternalStorageAppDataDirs(String packageName) {
    119             return buildPaths(getExternalDirs(), DIR_ANDROID, DIR_DATA, packageName);
    120         }
    121 
    122         public File[] buildExternalStorageAppMediaDirs(String packageName) {
    123             return buildPaths(getExternalDirs(), DIR_ANDROID, DIR_MEDIA, packageName);
    124         }
    125 
    126         public File[] buildExternalStorageAppObbDirs(String packageName) {
    127             return buildPaths(getExternalDirs(), DIR_ANDROID, DIR_OBB, packageName);
    128         }
    129 
    130         public File[] buildExternalStorageAppFilesDirs(String packageName) {
    131             return buildPaths(getExternalDirs(), DIR_ANDROID, DIR_DATA, packageName, DIR_FILES);
    132         }
    133 
    134         public File[] buildExternalStorageAppCacheDirs(String packageName) {
    135             return buildPaths(getExternalDirs(), DIR_ANDROID, DIR_DATA, packageName, DIR_CACHE);
    136         }
    137     }
    138 
    139     /**
    140      * Return root of the "system" partition holding the core Android OS.
    141      * Always present and mounted read-only.
    142      */
    143     public static File getRootDirectory() {
    144         return DIR_ANDROID_ROOT;
    145     }
    146 
    147     /** {@hide} */
    148     public static File getStorageDirectory() {
    149         return DIR_ANDROID_STORAGE;
    150     }
    151 
    152     /**
    153      * Return root directory of the "oem" partition holding OEM customizations,
    154      * if any. If present, the partition is mounted read-only.
    155      *
    156      * @hide
    157      */
    158     public static File getOemDirectory() {
    159         return DIR_OEM_ROOT;
    160     }
    161 
    162     /**
    163      * Return root directory of the "odm" partition holding ODM customizations,
    164      * if any. If present, the partition is mounted read-only.
    165      *
    166      * @hide
    167      */
    168     public static File getOdmDirectory() {
    169         return DIR_ODM_ROOT;
    170     }
    171 
    172     /**
    173      * Return root directory of the "vendor" partition that holds vendor-provided
    174      * software that should persist across simple reflashing of the "system" partition.
    175      * @hide
    176      */
    177     public static File getVendorDirectory() {
    178         return DIR_VENDOR_ROOT;
    179     }
    180 
    181     /**
    182      * Return the system directory for a user. This is for use by system
    183      * services to store files relating to the user. This directory will be
    184      * automatically deleted when the user is removed.
    185      *
    186      * @deprecated This directory is valid and still exists, but callers should
    187      *             <em>strongly</em> consider switching to
    188      *             {@link #getDataSystemCeDirectory(int)} which is protected
    189      *             with user credentials or
    190      *             {@link #getDataSystemDeDirectory(int)} which supports fast
    191      *             user wipe.
    192      * @hide
    193      */
    194     @Deprecated
    195     public static File getUserSystemDirectory(int userId) {
    196         return new File(new File(getDataSystemDirectory(), "users"), Integer.toString(userId));
    197     }
    198 
    199     /**
    200      * Returns the config directory for a user. This is for use by system
    201      * services to store files relating to the user which should be readable by
    202      * any app running as that user.
    203      *
    204      * @deprecated This directory is valid and still exists, but callers should
    205      *             <em>strongly</em> consider switching to
    206      *             {@link #getDataMiscCeDirectory(int)} which is protected with
    207      *             user credentials or {@link #getDataMiscDeDirectory(int)}
    208      *             which supports fast user wipe.
    209      * @hide
    210      */
    211     @Deprecated
    212     public static File getUserConfigDirectory(int userId) {
    213         return new File(new File(new File(
    214                 getDataDirectory(), "misc"), "user"), Integer.toString(userId));
    215     }
    216 
    217     /**
    218      * Return the user data directory.
    219      */
    220     public static File getDataDirectory() {
    221         return DIR_ANDROID_DATA;
    222     }
    223 
    224     /** {@hide} */
    225     public static File getDataDirectory(String volumeUuid) {
    226         if (TextUtils.isEmpty(volumeUuid)) {
    227             return DIR_ANDROID_DATA;
    228         } else {
    229             return new File("/mnt/expand/" + volumeUuid);
    230         }
    231     }
    232 
    233     /** {@hide} */
    234     public static File getExpandDirectory() {
    235         return DIR_ANDROID_EXPAND;
    236     }
    237 
    238     /** {@hide} */
    239     public static File getDataSystemDirectory() {
    240         return new File(getDataDirectory(), "system");
    241     }
    242 
    243     /**
    244      * Returns the base directory for per-user system directory, device encrypted.
    245      * {@hide}
    246      */
    247     public static File getDataSystemDeDirectory() {
    248         return buildPath(getDataDirectory(), "system_de");
    249     }
    250 
    251     /**
    252      * Returns the base directory for per-user system directory, credential encrypted.
    253      * {@hide}
    254      */
    255     public static File getDataSystemCeDirectory() {
    256         return buildPath(getDataDirectory(), "system_ce");
    257     }
    258 
    259     /** {@hide} */
    260     public static File getDataSystemCeDirectory(int userId) {
    261         return buildPath(getDataDirectory(), "system_ce", String.valueOf(userId));
    262     }
    263 
    264     /** {@hide} */
    265     public static File getDataSystemDeDirectory(int userId) {
    266         return buildPath(getDataDirectory(), "system_de", String.valueOf(userId));
    267     }
    268 
    269     /** {@hide} */
    270     public static File getDataMiscDirectory() {
    271         return new File(getDataDirectory(), "misc");
    272     }
    273 
    274     /** {@hide} */
    275     public static File getDataMiscCeDirectory() {
    276         return buildPath(getDataDirectory(), "misc_ce");
    277     }
    278 
    279     /** {@hide} */
    280     public static File getDataMiscCeDirectory(int userId) {
    281         return buildPath(getDataDirectory(), "misc_ce", String.valueOf(userId));
    282     }
    283 
    284     /** {@hide} */
    285     public static File getDataMiscDeDirectory(int userId) {
    286         return buildPath(getDataDirectory(), "misc_de", String.valueOf(userId));
    287     }
    288 
    289     private static File getDataProfilesDeDirectory(int userId) {
    290         return buildPath(getDataDirectory(), "misc", "profiles", "cur", String.valueOf(userId));
    291     }
    292 
    293     /** {@hide} */
    294     public static File getReferenceProfile(String packageName) {
    295         return buildPath(getDataDirectory(), "misc", "profiles", "ref", packageName);
    296     }
    297 
    298     /** {@hide} */
    299     public static File getDataProfilesDePackageDirectory(int userId, String packageName) {
    300         return buildPath(getDataProfilesDeDirectory(userId), packageName);
    301     }
    302 
    303     /** {@hide} */
    304     public static File getDataAppDirectory(String volumeUuid) {
    305         return new File(getDataDirectory(volumeUuid), "app");
    306     }
    307 
    308     /** {@hide} */
    309     public static File getDataUserCeDirectory(String volumeUuid) {
    310         return new File(getDataDirectory(volumeUuid), "user");
    311     }
    312 
    313     /** {@hide} */
    314     public static File getDataUserCeDirectory(String volumeUuid, int userId) {
    315         return new File(getDataUserCeDirectory(volumeUuid), String.valueOf(userId));
    316     }
    317 
    318     /** {@hide} */
    319     public static File getDataUserCePackageDirectory(String volumeUuid, int userId,
    320             String packageName) {
    321         // TODO: keep consistent with installd
    322         return new File(getDataUserCeDirectory(volumeUuid, userId), packageName);
    323     }
    324 
    325     /** {@hide} */
    326     public static File getDataUserDeDirectory(String volumeUuid) {
    327         return new File(getDataDirectory(volumeUuid), "user_de");
    328     }
    329 
    330     /** {@hide} */
    331     public static File getDataUserDeDirectory(String volumeUuid, int userId) {
    332         return new File(getDataUserDeDirectory(volumeUuid), String.valueOf(userId));
    333     }
    334 
    335     /** {@hide} */
    336     public static File getDataUserDePackageDirectory(String volumeUuid, int userId,
    337             String packageName) {
    338         // TODO: keep consistent with installd
    339         return new File(getDataUserDeDirectory(volumeUuid, userId), packageName);
    340     }
    341 
    342     /**
    343      * Return preloads directory.
    344      * <p>This directory may contain pre-loaded content such as
    345      * {@link #getDataPreloadsDemoDirectory() demo videos} and
    346      * {@link #getDataPreloadsAppsDirectory() APK files} .
    347      * {@hide}
    348      */
    349     public static File getDataPreloadsDirectory() {
    350         return new File(getDataDirectory(), "preloads");
    351     }
    352 
    353     /**
    354      * @see #getDataPreloadsDirectory()
    355      * {@hide}
    356      */
    357     public static File getDataPreloadsDemoDirectory() {
    358         return new File(getDataPreloadsDirectory(), "demo");
    359     }
    360 
    361     /**
    362      * @see #getDataPreloadsDirectory()
    363      * {@hide}
    364      */
    365     public static File getDataPreloadsAppsDirectory() {
    366         return new File(getDataPreloadsDirectory(), "apps");
    367     }
    368 
    369     /**
    370      * @see #getDataPreloadsDirectory()
    371      * {@hide}
    372      */
    373     public static File getDataPreloadsMediaDirectory() {
    374         return new File(getDataPreloadsDirectory(), "media");
    375     }
    376 
    377     /**
    378      * Returns location of preloaded cache directory for package name
    379      * @see #getDataPreloadsDirectory()
    380      * {@hide}
    381      */
    382     public static File getDataPreloadsFileCacheDirectory(String packageName) {
    383         return new File(getDataPreloadsFileCacheDirectory(), packageName);
    384     }
    385 
    386     /**
    387      * Returns location of preloaded cache directory.
    388      * @see #getDataPreloadsDirectory()
    389      * {@hide}
    390      */
    391     public static File getDataPreloadsFileCacheDirectory() {
    392         return new File(getDataPreloadsDirectory(), "file_cache");
    393     }
    394 
    395     /**
    396      * Return the primary shared/external storage directory. This directory may
    397      * not currently be accessible if it has been mounted by the user on their
    398      * computer, has been removed from the device, or some other problem has
    399      * happened. You can determine its current state with
    400      * {@link #getExternalStorageState()}.
    401      * <p>
    402      * <em>Note: don't be confused by the word "external" here. This directory
    403      * can better be thought as media/shared storage. It is a filesystem that
    404      * can hold a relatively large amount of data and that is shared across all
    405      * applications (does not enforce permissions). Traditionally this is an SD
    406      * card, but it may also be implemented as built-in storage in a device that
    407      * is distinct from the protected internal storage and can be mounted as a
    408      * filesystem on a computer.</em>
    409      * <p>
    410      * On devices with multiple users (as described by {@link UserManager}),
    411      * each user has their own isolated shared storage. Applications only have
    412      * access to the shared storage for the user they're running as.
    413      * <p>
    414      * In devices with multiple shared/external storage directories, this
    415      * directory represents the primary storage that the user will interact
    416      * with. Access to secondary storage is available through
    417      * {@link Context#getExternalFilesDirs(String)},
    418      * {@link Context#getExternalCacheDirs()}, and
    419      * {@link Context#getExternalMediaDirs()}.
    420      * <p>
    421      * Applications should not directly use this top-level directory, in order
    422      * to avoid polluting the user's root namespace. Any files that are private
    423      * to the application should be placed in a directory returned by
    424      * {@link android.content.Context#getExternalFilesDir
    425      * Context.getExternalFilesDir}, which the system will take care of deleting
    426      * if the application is uninstalled. Other shared files should be placed in
    427      * one of the directories returned by
    428      * {@link #getExternalStoragePublicDirectory}.
    429      * <p>
    430      * Writing to this path requires the
    431      * {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE} permission,
    432      * and starting in {@link android.os.Build.VERSION_CODES#KITKAT}, read access requires the
    433      * {@link android.Manifest.permission#READ_EXTERNAL_STORAGE} permission,
    434      * which is automatically granted if you hold the write permission.
    435      * <p>
    436      * Starting in {@link android.os.Build.VERSION_CODES#KITKAT}, if your
    437      * application only needs to store internal data, consider using
    438      * {@link Context#getExternalFilesDir(String)},
    439      * {@link Context#getExternalCacheDir()}, or
    440      * {@link Context#getExternalMediaDirs()}, which require no permissions to
    441      * read or write.
    442      * <p>
    443      * This path may change between platform versions, so applications should
    444      * only persist relative paths.
    445      * <p>
    446      * Here is an example of typical code to monitor the state of external
    447      * storage:
    448      * <p>
    449      * {@sample development/samples/ApiDemos/src/com/example/android/apis/content/ExternalStorage.java
    450      * monitor_storage}
    451      *
    452      * @see #getExternalStorageState()
    453      * @see #isExternalStorageRemovable()
    454      */
    455     public static File getExternalStorageDirectory() {
    456         throwIfUserRequired();
    457         return sCurrentUser.getExternalDirs()[0];
    458     }
    459 
    460     /** {@hide} */
    461     public static File getLegacyExternalStorageDirectory() {
    462         return new File(System.getenv(ENV_EXTERNAL_STORAGE));
    463     }
    464 
    465     /** {@hide} */
    466     public static File getLegacyExternalStorageObbDirectory() {
    467         return buildPath(getLegacyExternalStorageDirectory(), DIR_ANDROID, DIR_OBB);
    468     }
    469 
    470     /**
    471      * Standard directory in which to place any audio files that should be
    472      * in the regular list of music for the user.
    473      * This may be combined with
    474      * {@link #DIRECTORY_PODCASTS}, {@link #DIRECTORY_NOTIFICATIONS},
    475      * {@link #DIRECTORY_ALARMS}, and {@link #DIRECTORY_RINGTONES} as a series
    476      * of directories to categories a particular audio file as more than one
    477      * type.
    478      */
    479     public static String DIRECTORY_MUSIC = "Music";
    480 
    481     /**
    482      * Standard directory in which to place any audio files that should be
    483      * in the list of podcasts that the user can select (not as regular
    484      * music).
    485      * This may be combined with {@link #DIRECTORY_MUSIC},
    486      * {@link #DIRECTORY_NOTIFICATIONS},
    487      * {@link #DIRECTORY_ALARMS}, and {@link #DIRECTORY_RINGTONES} as a series
    488      * of directories to categories a particular audio file as more than one
    489      * type.
    490      */
    491     public static String DIRECTORY_PODCASTS = "Podcasts";
    492 
    493     /**
    494      * Standard directory in which to place any audio files that should be
    495      * in the list of ringtones that the user can select (not as regular
    496      * music).
    497      * This may be combined with {@link #DIRECTORY_MUSIC},
    498      * {@link #DIRECTORY_PODCASTS}, {@link #DIRECTORY_NOTIFICATIONS}, and
    499      * {@link #DIRECTORY_ALARMS} as a series
    500      * of directories to categories a particular audio file as more than one
    501      * type.
    502      */
    503     public static String DIRECTORY_RINGTONES = "Ringtones";
    504 
    505     /**
    506      * Standard directory in which to place any audio files that should be
    507      * in the list of alarms that the user can select (not as regular
    508      * music).
    509      * This may be combined with {@link #DIRECTORY_MUSIC},
    510      * {@link #DIRECTORY_PODCASTS}, {@link #DIRECTORY_NOTIFICATIONS},
    511      * and {@link #DIRECTORY_RINGTONES} as a series
    512      * of directories to categories a particular audio file as more than one
    513      * type.
    514      */
    515     public static String DIRECTORY_ALARMS = "Alarms";
    516 
    517     /**
    518      * Standard directory in which to place any audio files that should be
    519      * in the list of notifications that the user can select (not as regular
    520      * music).
    521      * This may be combined with {@link #DIRECTORY_MUSIC},
    522      * {@link #DIRECTORY_PODCASTS},
    523      * {@link #DIRECTORY_ALARMS}, and {@link #DIRECTORY_RINGTONES} as a series
    524      * of directories to categories a particular audio file as more than one
    525      * type.
    526      */
    527     public static String DIRECTORY_NOTIFICATIONS = "Notifications";
    528 
    529     /**
    530      * Standard directory in which to place pictures that are available to
    531      * the user.  Note that this is primarily a convention for the top-level
    532      * public directory, as the media scanner will find and collect pictures
    533      * in any directory.
    534      */
    535     public static String DIRECTORY_PICTURES = "Pictures";
    536 
    537     /**
    538      * Standard directory in which to place movies that are available to
    539      * the user.  Note that this is primarily a convention for the top-level
    540      * public directory, as the media scanner will find and collect movies
    541      * in any directory.
    542      */
    543     public static String DIRECTORY_MOVIES = "Movies";
    544 
    545     /**
    546      * Standard directory in which to place files that have been downloaded by
    547      * the user.  Note that this is primarily a convention for the top-level
    548      * public directory, you are free to download files anywhere in your own
    549      * private directories.  Also note that though the constant here is
    550      * named DIRECTORY_DOWNLOADS (plural), the actual file name is non-plural for
    551      * backwards compatibility reasons.
    552      */
    553     public static String DIRECTORY_DOWNLOADS = "Download";
    554 
    555     /**
    556      * The traditional location for pictures and videos when mounting the
    557      * device as a camera.  Note that this is primarily a convention for the
    558      * top-level public directory, as this convention makes no sense elsewhere.
    559      */
    560     public static String DIRECTORY_DCIM = "DCIM";
    561 
    562     /**
    563      * Standard directory in which to place documents that have been created by
    564      * the user.
    565      */
    566     public static String DIRECTORY_DOCUMENTS = "Documents";
    567 
    568     /**
    569      * List of standard storage directories.
    570      * <p>
    571      * Each of its values have its own constant:
    572      * <ul>
    573      *   <li>{@link #DIRECTORY_MUSIC}
    574      *   <li>{@link #DIRECTORY_PODCASTS}
    575      *   <li>{@link #DIRECTORY_ALARMS}
    576      *   <li>{@link #DIRECTORY_RINGTONES}
    577      *   <li>{@link #DIRECTORY_NOTIFICATIONS}
    578      *   <li>{@link #DIRECTORY_PICTURES}
    579      *   <li>{@link #DIRECTORY_MOVIES}
    580      *   <li>{@link #DIRECTORY_DOWNLOADS}
    581      *   <li>{@link #DIRECTORY_DCIM}
    582      *   <li>{@link #DIRECTORY_DOCUMENTS}
    583      * </ul>
    584      * @hide
    585      */
    586     public static final String[] STANDARD_DIRECTORIES = {
    587             DIRECTORY_MUSIC,
    588             DIRECTORY_PODCASTS,
    589             DIRECTORY_RINGTONES,
    590             DIRECTORY_ALARMS,
    591             DIRECTORY_NOTIFICATIONS,
    592             DIRECTORY_PICTURES,
    593             DIRECTORY_MOVIES,
    594             DIRECTORY_DOWNLOADS,
    595             DIRECTORY_DCIM,
    596             DIRECTORY_DOCUMENTS
    597     };
    598 
    599     /**
    600      * @hide
    601      */
    602     public static boolean isStandardDirectory(String dir) {
    603         for (String valid : STANDARD_DIRECTORIES) {
    604             if (valid.equals(dir)) {
    605                 return true;
    606             }
    607         }
    608         return false;
    609     }
    610 
    611     /**
    612      * Get a top-level shared/external storage directory for placing files of a
    613      * particular type. This is where the user will typically place and manage
    614      * their own files, so you should be careful about what you put here to
    615      * ensure you don't erase their files or get in the way of their own
    616      * organization.
    617      * <p>
    618      * On devices with multiple users (as described by {@link UserManager}),
    619      * each user has their own isolated shared storage. Applications only have
    620      * access to the shared storage for the user they're running as.
    621      * </p>
    622      * <p>
    623      * Here is an example of typical code to manipulate a picture on the public
    624      * shared storage:
    625      * </p>
    626      * {@sample development/samples/ApiDemos/src/com/example/android/apis/content/ExternalStorage.java
    627      * public_picture}
    628      *
    629      * @param type The type of storage directory to return. Should be one of
    630      *            {@link #DIRECTORY_MUSIC}, {@link #DIRECTORY_PODCASTS},
    631      *            {@link #DIRECTORY_RINGTONES}, {@link #DIRECTORY_ALARMS},
    632      *            {@link #DIRECTORY_NOTIFICATIONS}, {@link #DIRECTORY_PICTURES},
    633      *            {@link #DIRECTORY_MOVIES}, {@link #DIRECTORY_DOWNLOADS},
    634      *            {@link #DIRECTORY_DCIM}, or {@link #DIRECTORY_DOCUMENTS}. May not be null.
    635      * @return Returns the File path for the directory. Note that this directory
    636      *         may not yet exist, so you must make sure it exists before using
    637      *         it such as with {@link File#mkdirs File.mkdirs()}.
    638      */
    639     public static File getExternalStoragePublicDirectory(String type) {
    640         throwIfUserRequired();
    641         return sCurrentUser.buildExternalStoragePublicDirs(type)[0];
    642     }
    643 
    644     /**
    645      * Returns the path for android-specific data on the SD card.
    646      * @hide
    647      */
    648     public static File[] buildExternalStorageAndroidDataDirs() {
    649         throwIfUserRequired();
    650         return sCurrentUser.buildExternalStorageAndroidDataDirs();
    651     }
    652 
    653     /**
    654      * Generates the raw path to an application's data
    655      * @hide
    656      */
    657     public static File[] buildExternalStorageAppDataDirs(String packageName) {
    658         throwIfUserRequired();
    659         return sCurrentUser.buildExternalStorageAppDataDirs(packageName);
    660     }
    661 
    662     /**
    663      * Generates the raw path to an application's media
    664      * @hide
    665      */
    666     public static File[] buildExternalStorageAppMediaDirs(String packageName) {
    667         throwIfUserRequired();
    668         return sCurrentUser.buildExternalStorageAppMediaDirs(packageName);
    669     }
    670 
    671     /**
    672      * Generates the raw path to an application's OBB files
    673      * @hide
    674      */
    675     public static File[] buildExternalStorageAppObbDirs(String packageName) {
    676         throwIfUserRequired();
    677         return sCurrentUser.buildExternalStorageAppObbDirs(packageName);
    678     }
    679 
    680     /**
    681      * Generates the path to an application's files.
    682      * @hide
    683      */
    684     public static File[] buildExternalStorageAppFilesDirs(String packageName) {
    685         throwIfUserRequired();
    686         return sCurrentUser.buildExternalStorageAppFilesDirs(packageName);
    687     }
    688 
    689     /**
    690      * Generates the path to an application's cache.
    691      * @hide
    692      */
    693     public static File[] buildExternalStorageAppCacheDirs(String packageName) {
    694         throwIfUserRequired();
    695         return sCurrentUser.buildExternalStorageAppCacheDirs(packageName);
    696     }
    697 
    698     /**
    699      * Return the download/cache content directory.
    700      */
    701     public static File getDownloadCacheDirectory() {
    702         return DIR_DOWNLOAD_CACHE;
    703     }
    704 
    705     /**
    706      * Unknown storage state, such as when a path isn't backed by known storage
    707      * media.
    708      *
    709      * @see #getExternalStorageState(File)
    710      */
    711     public static final String MEDIA_UNKNOWN = "unknown";
    712 
    713     /**
    714      * Storage state if the media is not present.
    715      *
    716      * @see #getExternalStorageState(File)
    717      */
    718     public static final String MEDIA_REMOVED = "removed";
    719 
    720     /**
    721      * Storage state if the media is present but not mounted.
    722      *
    723      * @see #getExternalStorageState(File)
    724      */
    725     public static final String MEDIA_UNMOUNTED = "unmounted";
    726 
    727     /**
    728      * Storage state if the media is present and being disk-checked.
    729      *
    730      * @see #getExternalStorageState(File)
    731      */
    732     public static final String MEDIA_CHECKING = "checking";
    733 
    734     /**
    735      * Storage state if the media is present but is blank or is using an
    736      * unsupported filesystem.
    737      *
    738      * @see #getExternalStorageState(File)
    739      */
    740     public static final String MEDIA_NOFS = "nofs";
    741 
    742     /**
    743      * Storage state if the media is present and mounted at its mount point with
    744      * read/write access.
    745      *
    746      * @see #getExternalStorageState(File)
    747      */
    748     public static final String MEDIA_MOUNTED = "mounted";
    749 
    750     /**
    751      * Storage state if the media is present and mounted at its mount point with
    752      * read-only access.
    753      *
    754      * @see #getExternalStorageState(File)
    755      */
    756     public static final String MEDIA_MOUNTED_READ_ONLY = "mounted_ro";
    757 
    758     /**
    759      * Storage state if the media is present not mounted, and shared via USB
    760      * mass storage.
    761      *
    762      * @see #getExternalStorageState(File)
    763      */
    764     public static final String MEDIA_SHARED = "shared";
    765 
    766     /**
    767      * Storage state if the media was removed before it was unmounted.
    768      *
    769      * @see #getExternalStorageState(File)
    770      */
    771     public static final String MEDIA_BAD_REMOVAL = "bad_removal";
    772 
    773     /**
    774      * Storage state if the media is present but cannot be mounted. Typically
    775      * this happens if the file system on the media is corrupted.
    776      *
    777      * @see #getExternalStorageState(File)
    778      */
    779     public static final String MEDIA_UNMOUNTABLE = "unmountable";
    780 
    781     /**
    782      * Storage state if the media is in the process of being ejected.
    783      *
    784      * @see #getExternalStorageState(File)
    785      */
    786     public static final String MEDIA_EJECTING = "ejecting";
    787 
    788     /**
    789      * Returns the current state of the primary shared/external storage media.
    790      *
    791      * @see #getExternalStorageDirectory()
    792      * @return one of {@link #MEDIA_UNKNOWN}, {@link #MEDIA_REMOVED},
    793      *         {@link #MEDIA_UNMOUNTED}, {@link #MEDIA_CHECKING},
    794      *         {@link #MEDIA_NOFS}, {@link #MEDIA_MOUNTED},
    795      *         {@link #MEDIA_MOUNTED_READ_ONLY}, {@link #MEDIA_SHARED},
    796      *         {@link #MEDIA_BAD_REMOVAL}, or {@link #MEDIA_UNMOUNTABLE}.
    797      */
    798     public static String getExternalStorageState() {
    799         final File externalDir = sCurrentUser.getExternalDirs()[0];
    800         return getExternalStorageState(externalDir);
    801     }
    802 
    803     /**
    804      * @deprecated use {@link #getExternalStorageState(File)}
    805      */
    806     @Deprecated
    807     public static String getStorageState(File path) {
    808         return getExternalStorageState(path);
    809     }
    810 
    811     /**
    812      * Returns the current state of the shared/external storage media at the
    813      * given path.
    814      *
    815      * @return one of {@link #MEDIA_UNKNOWN}, {@link #MEDIA_REMOVED},
    816      *         {@link #MEDIA_UNMOUNTED}, {@link #MEDIA_CHECKING},
    817      *         {@link #MEDIA_NOFS}, {@link #MEDIA_MOUNTED},
    818      *         {@link #MEDIA_MOUNTED_READ_ONLY}, {@link #MEDIA_SHARED},
    819      *         {@link #MEDIA_BAD_REMOVAL}, or {@link #MEDIA_UNMOUNTABLE}.
    820      */
    821     public static String getExternalStorageState(File path) {
    822         final StorageVolume volume = StorageManager.getStorageVolume(path, UserHandle.myUserId());
    823         if (volume != null) {
    824             return volume.getState();
    825         } else {
    826             return MEDIA_UNKNOWN;
    827         }
    828     }
    829 
    830     /**
    831      * Returns whether the primary shared/external storage media is physically
    832      * removable.
    833      *
    834      * @return true if the storage device can be removed (such as an SD card),
    835      *         or false if the storage device is built in and cannot be
    836      *         physically removed.
    837      */
    838     public static boolean isExternalStorageRemovable() {
    839         if (isStorageDisabled()) return false;
    840         final File externalDir = sCurrentUser.getExternalDirs()[0];
    841         return isExternalStorageRemovable(externalDir);
    842     }
    843 
    844     /**
    845      * Returns whether the shared/external storage media at the given path is
    846      * physically removable.
    847      *
    848      * @return true if the storage device can be removed (such as an SD card),
    849      *         or false if the storage device is built in and cannot be
    850      *         physically removed.
    851      * @throws IllegalArgumentException if the path is not a valid storage
    852      *             device.
    853      */
    854     public static boolean isExternalStorageRemovable(File path) {
    855         final StorageVolume volume = StorageManager.getStorageVolume(path, UserHandle.myUserId());
    856         if (volume != null) {
    857             return volume.isRemovable();
    858         } else {
    859             throw new IllegalArgumentException("Failed to find storage device at " + path);
    860         }
    861     }
    862 
    863     /**
    864      * Returns whether the primary shared/external storage media is emulated.
    865      * <p>
    866      * The contents of emulated storage devices are backed by a private user
    867      * data partition, which means there is little benefit to apps storing data
    868      * here instead of the private directories returned by
    869      * {@link Context#getFilesDir()}, etc.
    870      * <p>
    871      * This returns true when emulated storage is backed by either internal
    872      * storage or an adopted storage device.
    873      *
    874      * @see DevicePolicyManager#setStorageEncryption(android.content.ComponentName,
    875      *      boolean)
    876      */
    877     public static boolean isExternalStorageEmulated() {
    878         if (isStorageDisabled()) return false;
    879         final File externalDir = sCurrentUser.getExternalDirs()[0];
    880         return isExternalStorageEmulated(externalDir);
    881     }
    882 
    883     /**
    884      * Returns whether the shared/external storage media at the given path is
    885      * emulated.
    886      * <p>
    887      * The contents of emulated storage devices are backed by a private user
    888      * data partition, which means there is little benefit to apps storing data
    889      * here instead of the private directories returned by
    890      * {@link Context#getFilesDir()}, etc.
    891      * <p>
    892      * This returns true when emulated storage is backed by either internal
    893      * storage or an adopted storage device.
    894      *
    895      * @throws IllegalArgumentException if the path is not a valid storage
    896      *             device.
    897      */
    898     public static boolean isExternalStorageEmulated(File path) {
    899         final StorageVolume volume = StorageManager.getStorageVolume(path, UserHandle.myUserId());
    900         if (volume != null) {
    901             return volume.isEmulated();
    902         } else {
    903             throw new IllegalArgumentException("Failed to find storage device at " + path);
    904         }
    905     }
    906 
    907     static File getDirectory(String variableName, String defaultPath) {
    908         String path = System.getenv(variableName);
    909         return path == null ? new File(defaultPath) : new File(path);
    910     }
    911 
    912     /** {@hide} */
    913     public static void setUserRequired(boolean userRequired) {
    914         sUserRequired = userRequired;
    915     }
    916 
    917     private static void throwIfUserRequired() {
    918         if (sUserRequired) {
    919             Log.wtf(TAG, "Path requests must specify a user by using UserEnvironment",
    920                     new Throwable());
    921         }
    922     }
    923 
    924     /**
    925      * Append path segments to each given base path, returning result.
    926      *
    927      * @hide
    928      */
    929     public static File[] buildPaths(File[] base, String... segments) {
    930         File[] result = new File[base.length];
    931         for (int i = 0; i < base.length; i++) {
    932             result[i] = buildPath(base[i], segments);
    933         }
    934         return result;
    935     }
    936 
    937     /**
    938      * Append path segments to given base path, returning result.
    939      *
    940      * @hide
    941      */
    942     public static File buildPath(File base, String... segments) {
    943         File cur = base;
    944         for (String segment : segments) {
    945             if (cur == null) {
    946                 cur = new File(segment);
    947             } else {
    948                 cur = new File(cur, segment);
    949             }
    950         }
    951         return cur;
    952     }
    953 
    954     private static boolean isStorageDisabled() {
    955         return SystemProperties.getBoolean("config.disable_storage", false);
    956     }
    957 
    958     /**
    959      * If the given path exists on emulated external storage, return the
    960      * translated backing path hosted on internal storage. This bypasses any
    961      * emulation later, improving performance. This is <em>only</em> suitable
    962      * for read-only access.
    963      * <p>
    964      * Returns original path if given path doesn't meet these criteria. Callers
    965      * must hold {@link android.Manifest.permission#WRITE_MEDIA_STORAGE}
    966      * permission.
    967      *
    968      * @hide
    969      */
    970     public static File maybeTranslateEmulatedPathToInternal(File path) {
    971         return StorageManager.maybeTranslateEmulatedPathToInternal(path);
    972     }
    973 }
    974