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