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