2 * Copyright (C) 2007 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 import android.annotation.TestApi;
20 import android.app.admin.DevicePolicyManager;
21 import android.content.Context;
22 import android.os.storage.StorageManager;
23 import android.os.storage.StorageVolume;
24 import android.text.TextUtils;
25 import android.util.Log;
28 import java.util.LinkedList;
31 * Provides access to environment variables.
33 public class Environment {
34 private static final String TAG = "Environment";
36 // NOTE: keep credential-protected paths in sync with StrictMode.java
38 private static final String ENV_EXTERNAL_STORAGE = "EXTERNAL_STORAGE";
39 private static final String ENV_ANDROID_ROOT = "ANDROID_ROOT";
40 private static final String ENV_ANDROID_DATA = "ANDROID_DATA";
41 private static final String ENV_ANDROID_EXPAND = "ANDROID_EXPAND";
42 private static final String ENV_ANDROID_STORAGE = "ANDROID_STORAGE";
43 private static final String ENV_DOWNLOAD_CACHE = "DOWNLOAD_CACHE";
44 private static final String ENV_OEM_ROOT = "OEM_ROOT";
45 private static final String ENV_ODM_ROOT = "ODM_ROOT";
46 private static final String ENV_VENDOR_ROOT = "VENDOR_ROOT";
47 private static final String ENV_PRODUCT_ROOT = "PRODUCT_ROOT";
50 public static final String DIR_ANDROID = "Android";
51 private static final String DIR_DATA = "data";
52 private static final String DIR_MEDIA = "media";
53 private static final String DIR_OBB = "obb";
54 private static final String DIR_FILES = "files";
55 private static final String DIR_CACHE = "cache";
59 public static final String DIRECTORY_ANDROID = DIR_ANDROID;
61 private static final File DIR_ANDROID_ROOT = getDirectory(ENV_ANDROID_ROOT, "/system");
62 private static final File DIR_ANDROID_DATA = getDirectory(ENV_ANDROID_DATA, "/data");
63 private static final File DIR_ANDROID_EXPAND = getDirectory(ENV_ANDROID_EXPAND, "/mnt/expand");
64 private static final File DIR_ANDROID_STORAGE = getDirectory(ENV_ANDROID_STORAGE, "/storage");
65 private static final File DIR_DOWNLOAD_CACHE = getDirectory(ENV_DOWNLOAD_CACHE, "/cache");
66 private static final File DIR_OEM_ROOT = getDirectory(ENV_OEM_ROOT, "/oem");
67 private static final File DIR_ODM_ROOT = getDirectory(ENV_ODM_ROOT, "/odm");
68 private static final File DIR_VENDOR_ROOT = getDirectory(ENV_VENDOR_ROOT, "/vendor");
69 private static final File DIR_PRODUCT_ROOT = getDirectory(ENV_PRODUCT_ROOT, "/product");
71 private static UserEnvironment sCurrentUser;
72 private static boolean sUserRequired;
79 public static void initForCurrentUser() {
80 final int userId = UserHandle.myUserId();
81 sCurrentUser = new UserEnvironment(userId);
85 public static class UserEnvironment {
86 private final int mUserId;
88 public UserEnvironment(int userId) {
92 public File[] getExternalDirs() {
93 final StorageVolume[] volumes = StorageManager.getVolumeList(mUserId,
94 StorageManager.FLAG_FOR_WRITE);
95 final File[] files = new File[volumes.length];
96 for (int i = 0; i < volumes.length; i++) {
97 files[i] = volumes[i].getPathFile();
103 public File getExternalStorageDirectory() {
104 return getExternalDirs()[0];
108 public File getExternalStoragePublicDirectory(String type) {
109 return buildExternalStoragePublicDirs(type)[0];
112 public File[] buildExternalStoragePublicDirs(String type) {
113 return buildPaths(getExternalDirs(), type);
116 public File[] buildExternalStorageAndroidDataDirs() {
117 return buildPaths(getExternalDirs(), DIR_ANDROID, DIR_DATA);
120 public File[] buildExternalStorageAndroidObbDirs() {
121 return buildPaths(getExternalDirs(), DIR_ANDROID, DIR_OBB);
124 public File[] buildExternalStorageAppDataDirs(String packageName) {
125 return buildPaths(getExternalDirs(), DIR_ANDROID, DIR_DATA, packageName);
128 public File[] buildExternalStorageAppMediaDirs(String packageName) {
129 return buildPaths(getExternalDirs(), DIR_ANDROID, DIR_MEDIA, packageName);
132 public File[] buildExternalStorageAppObbDirs(String packageName) {
133 return buildPaths(getExternalDirs(), DIR_ANDROID, DIR_OBB, packageName);
136 public File[] buildExternalStorageAppFilesDirs(String packageName) {
137 return buildPaths(getExternalDirs(), DIR_ANDROID, DIR_DATA, packageName, DIR_FILES);
140 public File[] buildExternalStorageAppCacheDirs(String packageName) {
141 return buildPaths(getExternalDirs(), DIR_ANDROID, DIR_DATA, packageName, DIR_CACHE);
146 * Return root of the "system" partition holding the core Android OS.
147 * Always present and mounted read-only.
149 public static File getRootDirectory() {
150 return DIR_ANDROID_ROOT;
154 public static File getStorageDirectory() {
155 return DIR_ANDROID_STORAGE;
159 * Return root directory of the "oem" partition holding OEM customizations,
160 * if any. If present, the partition is mounted read-only.
164 public static File getOemDirectory() {
169 * Return root directory of the "odm" partition holding ODM customizations,
170 * if any. If present, the partition is mounted read-only.
174 public static File getOdmDirectory() {
179 * Return root directory of the "vendor" partition that holds vendor-provided
180 * software that should persist across simple reflashing of the "system" partition.
183 public static File getVendorDirectory() {
184 return DIR_VENDOR_ROOT;
188 * Return root directory of the "product" partition holding product-specific
189 * customizations if any. If present, the partition is mounted read-only.
193 public static File getProductDirectory() {
194 return DIR_PRODUCT_ROOT;
198 * Return the system directory for a user. This is for use by system
199 * services to store files relating to the user. This directory will be
200 * automatically deleted when the user is removed.
202 * @deprecated This directory is valid and still exists, but callers should
203 * <em>strongly</em> consider switching to
204 * {@link #getDataSystemCeDirectory(int)} which is protected
205 * with user credentials or
206 * {@link #getDataSystemDeDirectory(int)} which supports fast
211 public static File getUserSystemDirectory(int userId) {
212 return new File(new File(getDataSystemDirectory(), "users"), Integer.toString(userId));
216 * Returns the config directory for a user. This is for use by system
217 * services to store files relating to the user which should be readable by
218 * any app running as that user.
220 * @deprecated This directory is valid and still exists, but callers should
221 * <em>strongly</em> consider switching to
222 * {@link #getDataMiscCeDirectory(int)} which is protected with
223 * user credentials or {@link #getDataMiscDeDirectory(int)}
224 * which supports fast user wipe.
228 public static File getUserConfigDirectory(int userId) {
229 return new File(new File(new File(
230 getDataDirectory(), "misc"), "user"), Integer.toString(userId));
234 * Return the user data directory.
236 public static File getDataDirectory() {
237 return DIR_ANDROID_DATA;
241 public static File getDataDirectory(String volumeUuid) {
242 if (TextUtils.isEmpty(volumeUuid)) {
243 return DIR_ANDROID_DATA;
245 return new File("/mnt/expand/" + volumeUuid);
250 public static File getExpandDirectory() {
251 return DIR_ANDROID_EXPAND;
255 public static File getDataSystemDirectory() {
256 return new File(getDataDirectory(), "system");
260 * Returns the base directory for per-user system directory, device encrypted.
263 public static File getDataSystemDeDirectory() {
264 return buildPath(getDataDirectory(), "system_de");
268 * Returns the base directory for per-user system directory, credential encrypted.
271 public static File getDataSystemCeDirectory() {
272 return buildPath(getDataDirectory(), "system_ce");
276 public static File getDataSystemCeDirectory(int userId) {
277 return buildPath(getDataDirectory(), "system_ce", String.valueOf(userId));
281 public static File getDataSystemDeDirectory(int userId) {
282 return buildPath(getDataDirectory(), "system_de", String.valueOf(userId));
286 public static File getDataMiscDirectory() {
287 return new File(getDataDirectory(), "misc");
291 public static File getDataMiscCeDirectory() {
292 return buildPath(getDataDirectory(), "misc_ce");
296 public static File getDataMiscCeDirectory(int userId) {
297 return buildPath(getDataDirectory(), "misc_ce", String.valueOf(userId));
301 public static File getDataMiscDeDirectory(int userId) {
302 return buildPath(getDataDirectory(), "misc_de", String.valueOf(userId));
305 private static File getDataProfilesDeDirectory(int userId) {
306 return buildPath(getDataDirectory(), "misc", "profiles", "cur", String.valueOf(userId));
310 public static File getDataVendorCeDirectory(int userId) {
311 return buildPath(getDataDirectory(), "vendor_ce", String.valueOf(userId));
315 public static File getDataVendorDeDirectory(int userId) {
316 return buildPath(getDataDirectory(), "vendor_de", String.valueOf(userId));
320 public static File getDataRefProfilesDePackageDirectory(String packageName) {
321 return buildPath(getDataDirectory(), "misc", "profiles", "ref", packageName);
325 public static File getDataProfilesDePackageDirectory(int userId, String packageName) {
326 return buildPath(getDataProfilesDeDirectory(userId), packageName);
330 public static File getDataAppDirectory(String volumeUuid) {
331 return new File(getDataDirectory(volumeUuid), "app");
335 public static File getDataUserCeDirectory(String volumeUuid) {
336 return new File(getDataDirectory(volumeUuid), "user");
340 public static File getDataUserCeDirectory(String volumeUuid, int userId) {
341 return new File(getDataUserCeDirectory(volumeUuid), String.valueOf(userId));
345 public static File getDataUserCePackageDirectory(String volumeUuid, int userId,
346 String packageName) {
347 // TODO: keep consistent with installd
348 return new File(getDataUserCeDirectory(volumeUuid, userId), packageName);
352 public static File getDataUserDeDirectory(String volumeUuid) {
353 return new File(getDataDirectory(volumeUuid), "user_de");
357 public static File getDataUserDeDirectory(String volumeUuid, int userId) {
358 return new File(getDataUserDeDirectory(volumeUuid), String.valueOf(userId));
362 public static File getDataUserDePackageDirectory(String volumeUuid, int userId,
363 String packageName) {
364 // TODO: keep consistent with installd
365 return new File(getDataUserDeDirectory(volumeUuid, userId), packageName);
369 * Return preloads directory.
370 * <p>This directory may contain pre-loaded content such as
371 * {@link #getDataPreloadsDemoDirectory() demo videos} and
372 * {@link #getDataPreloadsAppsDirectory() APK files} .
375 public static File getDataPreloadsDirectory() {
376 return new File(getDataDirectory(), "preloads");
380 * @see #getDataPreloadsDirectory()
383 public static File getDataPreloadsDemoDirectory() {
384 return new File(getDataPreloadsDirectory(), "demo");
388 * @see #getDataPreloadsDirectory()
391 public static File getDataPreloadsAppsDirectory() {
392 return new File(getDataPreloadsDirectory(), "apps");
396 * @see #getDataPreloadsDirectory()
399 public static File getDataPreloadsMediaDirectory() {
400 return new File(getDataPreloadsDirectory(), "media");
404 * Returns location of preloaded cache directory for package name
405 * @see #getDataPreloadsDirectory()
408 public static File getDataPreloadsFileCacheDirectory(String packageName) {
409 return new File(getDataPreloadsFileCacheDirectory(), packageName);
413 * Returns location of preloaded cache directory.
414 * @see #getDataPreloadsDirectory()
417 public static File getDataPreloadsFileCacheDirectory() {
418 return new File(getDataPreloadsDirectory(), "file_cache");
422 * Return the primary shared/external storage directory. This directory may
423 * not currently be accessible if it has been mounted by the user on their
424 * computer, has been removed from the device, or some other problem has
425 * happened. You can determine its current state with
426 * {@link #getExternalStorageState()}.
428 * <em>Note: don't be confused by the word "external" here. This directory
429 * can better be thought as media/shared storage. It is a filesystem that
430 * can hold a relatively large amount of data and that is shared across all
431 * applications (does not enforce permissions). Traditionally this is an SD
432 * card, but it may also be implemented as built-in storage in a device that
433 * is distinct from the protected internal storage and can be mounted as a
434 * filesystem on a computer.</em>
436 * On devices with multiple users (as described by {@link UserManager}),
437 * each user has their own isolated shared storage. Applications only have
438 * access to the shared storage for the user they're running as.
440 * In devices with multiple shared/external storage directories, this
441 * directory represents the primary storage that the user will interact
442 * with. Access to secondary storage is available through
443 * {@link Context#getExternalFilesDirs(String)},
444 * {@link Context#getExternalCacheDirs()}, and
445 * {@link Context#getExternalMediaDirs()}.
447 * Applications should not directly use this top-level directory, in order
448 * to avoid polluting the user's root namespace. Any files that are private
449 * to the application should be placed in a directory returned by
450 * {@link android.content.Context#getExternalFilesDir
451 * Context.getExternalFilesDir}, which the system will take care of deleting
452 * if the application is uninstalled. Other shared files should be placed in
453 * one of the directories returned by
454 * {@link #getExternalStoragePublicDirectory}.
456 * Writing to this path requires the
457 * {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE} permission,
458 * and starting in {@link android.os.Build.VERSION_CODES#KITKAT}, read access requires the
459 * {@link android.Manifest.permission#READ_EXTERNAL_STORAGE} permission,
460 * which is automatically granted if you hold the write permission.
462 * Starting in {@link android.os.Build.VERSION_CODES#KITKAT}, if your
463 * application only needs to store internal data, consider using
464 * {@link Context#getExternalFilesDir(String)},
465 * {@link Context#getExternalCacheDir()}, or
466 * {@link Context#getExternalMediaDirs()}, which require no permissions to
469 * This path may change between platform versions, so applications should
470 * only persist relative paths.
472 * Here is an example of typical code to monitor the state of external
475 * {@sample development/samples/ApiDemos/src/com/example/android/apis/content/ExternalStorage.java
478 * @see #getExternalStorageState()
479 * @see #isExternalStorageRemovable()
481 public static File getExternalStorageDirectory() {
482 throwIfUserRequired();
483 return sCurrentUser.getExternalDirs()[0];
487 public static File getLegacyExternalStorageDirectory() {
488 return new File(System.getenv(ENV_EXTERNAL_STORAGE));
492 public static File getLegacyExternalStorageObbDirectory() {
493 return buildPath(getLegacyExternalStorageDirectory(), DIR_ANDROID, DIR_OBB);
497 * Standard directory in which to place any audio files that should be
498 * in the regular list of music for the user.
499 * This may be combined with
500 * {@link #DIRECTORY_PODCASTS}, {@link #DIRECTORY_NOTIFICATIONS},
501 * {@link #DIRECTORY_ALARMS}, and {@link #DIRECTORY_RINGTONES} as a series
502 * of directories to categories a particular audio file as more than one
505 public static String DIRECTORY_MUSIC = "Music";
508 * Standard directory in which to place any audio files that should be
509 * in the list of podcasts that the user can select (not as regular
511 * This may be combined with {@link #DIRECTORY_MUSIC},
512 * {@link #DIRECTORY_NOTIFICATIONS},
513 * {@link #DIRECTORY_ALARMS}, and {@link #DIRECTORY_RINGTONES} as a series
514 * of directories to categories a particular audio file as more than one
517 public static String DIRECTORY_PODCASTS = "Podcasts";
520 * Standard directory in which to place any audio files that should be
521 * in the list of ringtones that the user can select (not as regular
523 * This may be combined with {@link #DIRECTORY_MUSIC},
524 * {@link #DIRECTORY_PODCASTS}, {@link #DIRECTORY_NOTIFICATIONS}, and
525 * {@link #DIRECTORY_ALARMS} as a series
526 * of directories to categories a particular audio file as more than one
529 public static String DIRECTORY_RINGTONES = "Ringtones";
532 * Standard directory in which to place any audio files that should be
533 * in the list of alarms that the user can select (not as regular
535 * This may be combined with {@link #DIRECTORY_MUSIC},
536 * {@link #DIRECTORY_PODCASTS}, {@link #DIRECTORY_NOTIFICATIONS},
537 * and {@link #DIRECTORY_RINGTONES} as a series
538 * of directories to categories a particular audio file as more than one
541 public static String DIRECTORY_ALARMS = "Alarms";
544 * Standard directory in which to place any audio files that should be
545 * in the list of notifications that the user can select (not as regular
547 * This may be combined with {@link #DIRECTORY_MUSIC},
548 * {@link #DIRECTORY_PODCASTS},
549 * {@link #DIRECTORY_ALARMS}, and {@link #DIRECTORY_RINGTONES} as a series
550 * of directories to categories a particular audio file as more than one
553 public static String DIRECTORY_NOTIFICATIONS = "Notifications";
556 * Standard directory in which to place pictures that are available to
557 * the user. Note that this is primarily a convention for the top-level
558 * public directory, as the media scanner will find and collect pictures
561 public static String DIRECTORY_PICTURES = "Pictures";
564 * Standard directory in which to place movies that are available to
565 * the user. Note that this is primarily a convention for the top-level
566 * public directory, as the media scanner will find and collect movies
569 public static String DIRECTORY_MOVIES = "Movies";
572 * Standard directory in which to place files that have been downloaded by
573 * the user. Note that this is primarily a convention for the top-level
574 * public directory, you are free to download files anywhere in your own
575 * private directories. Also note that though the constant here is
576 * named DIRECTORY_DOWNLOADS (plural), the actual file name is non-plural for
577 * backwards compatibility reasons.
579 public static String DIRECTORY_DOWNLOADS = "Download";
582 * The traditional location for pictures and videos when mounting the
583 * device as a camera. Note that this is primarily a convention for the
584 * top-level public directory, as this convention makes no sense elsewhere.
586 public static String DIRECTORY_DCIM = "DCIM";
589 * Standard directory in which to place documents that have been created by
592 public static String DIRECTORY_DOCUMENTS = "Documents";
595 * List of standard storage directories.
597 * Each of its values have its own constant:
599 * <li>{@link #DIRECTORY_MUSIC}
600 * <li>{@link #DIRECTORY_PODCASTS}
601 * <li>{@link #DIRECTORY_ALARMS}
602 * <li>{@link #DIRECTORY_RINGTONES}
603 * <li>{@link #DIRECTORY_NOTIFICATIONS}
604 * <li>{@link #DIRECTORY_PICTURES}
605 * <li>{@link #DIRECTORY_MOVIES}
606 * <li>{@link #DIRECTORY_DOWNLOADS}
607 * <li>{@link #DIRECTORY_DCIM}
608 * <li>{@link #DIRECTORY_DOCUMENTS}
612 public static final String[] STANDARD_DIRECTORIES = {
617 DIRECTORY_NOTIFICATIONS,
628 public static boolean isStandardDirectory(String dir) {
629 for (String valid : STANDARD_DIRECTORIES) {
630 if (valid.equals(dir)) {
637 /** {@hide} */ public static final int HAS_MUSIC = 1 << 0;
638 /** {@hide} */ public static final int HAS_PODCASTS = 1 << 1;
639 /** {@hide} */ public static final int HAS_RINGTONES = 1 << 2;
640 /** {@hide} */ public static final int HAS_ALARMS = 1 << 3;
641 /** {@hide} */ public static final int HAS_NOTIFICATIONS = 1 << 4;
642 /** {@hide} */ public static final int HAS_PICTURES = 1 << 5;
643 /** {@hide} */ public static final int HAS_MOVIES = 1 << 6;
644 /** {@hide} */ public static final int HAS_DOWNLOADS = 1 << 7;
645 /** {@hide} */ public static final int HAS_DCIM = 1 << 8;
646 /** {@hide} */ public static final int HAS_DOCUMENTS = 1 << 9;
648 /** {@hide} */ public static final int HAS_ANDROID = 1 << 16;
649 /** {@hide} */ public static final int HAS_OTHER = 1 << 17;
652 * Classify the content types present on the given external storage device.
654 * This is typically useful for deciding if an inserted SD card is empty, or
655 * if it contains content like photos that should be preserved.
659 public static int classifyExternalStorageDirectory(File dir) {
661 for (File f : FileUtils.listFilesOrEmpty(dir)) {
662 if (f.isFile() && isInterestingFile(f)) {
664 } else if (f.isDirectory() && hasInterestingFiles(f)) {
665 final String name = f.getName();
666 if (DIRECTORY_MUSIC.equals(name)) res |= HAS_MUSIC;
667 else if (DIRECTORY_PODCASTS.equals(name)) res |= HAS_PODCASTS;
668 else if (DIRECTORY_RINGTONES.equals(name)) res |= HAS_RINGTONES;
669 else if (DIRECTORY_ALARMS.equals(name)) res |= HAS_ALARMS;
670 else if (DIRECTORY_NOTIFICATIONS.equals(name)) res |= HAS_NOTIFICATIONS;
671 else if (DIRECTORY_PICTURES.equals(name)) res |= HAS_PICTURES;
672 else if (DIRECTORY_MOVIES.equals(name)) res |= HAS_MOVIES;
673 else if (DIRECTORY_DOWNLOADS.equals(name)) res |= HAS_DOWNLOADS;
674 else if (DIRECTORY_DCIM.equals(name)) res |= HAS_DCIM;
675 else if (DIRECTORY_DOCUMENTS.equals(name)) res |= HAS_DOCUMENTS;
676 else if (DIRECTORY_ANDROID.equals(name)) res |= HAS_ANDROID;
677 else res |= HAS_OTHER;
683 private static boolean hasInterestingFiles(File dir) {
684 final LinkedList<File> explore = new LinkedList<>();
686 while (!explore.isEmpty()) {
688 for (File f : FileUtils.listFilesOrEmpty(dir)) {
689 if (isInterestingFile(f)) return true;
690 if (f.isDirectory()) explore.add(f);
696 private static boolean isInterestingFile(File file) {
698 final String name = file.getName().toLowerCase();
699 if (name.endsWith(".exe") || name.equals("autorun.inf")
700 || name.equals("launchpad.zip") || name.equals(".nomedia")) {
711 * Get a top-level shared/external storage directory for placing files of a
712 * particular type. This is where the user will typically place and manage
713 * their own files, so you should be careful about what you put here to
714 * ensure you don't erase their files or get in the way of their own
717 * On devices with multiple users (as described by {@link UserManager}),
718 * each user has their own isolated shared storage. Applications only have
719 * access to the shared storage for the user they're running as.
722 * Here is an example of typical code to manipulate a picture on the public
725 * {@sample development/samples/ApiDemos/src/com/example/android/apis/content/ExternalStorage.java
728 * @param type The type of storage directory to return. Should be one of
729 * {@link #DIRECTORY_MUSIC}, {@link #DIRECTORY_PODCASTS},
730 * {@link #DIRECTORY_RINGTONES}, {@link #DIRECTORY_ALARMS},
731 * {@link #DIRECTORY_NOTIFICATIONS}, {@link #DIRECTORY_PICTURES},
732 * {@link #DIRECTORY_MOVIES}, {@link #DIRECTORY_DOWNLOADS},
733 * {@link #DIRECTORY_DCIM}, or {@link #DIRECTORY_DOCUMENTS}. May not be null.
734 * @return Returns the File path for the directory. Note that this directory
735 * may not yet exist, so you must make sure it exists before using
736 * it such as with {@link File#mkdirs File.mkdirs()}.
738 public static File getExternalStoragePublicDirectory(String type) {
739 throwIfUserRequired();
740 return sCurrentUser.buildExternalStoragePublicDirs(type)[0];
744 * Returns the path for android-specific data on the SD card.
747 public static File[] buildExternalStorageAndroidDataDirs() {
748 throwIfUserRequired();
749 return sCurrentUser.buildExternalStorageAndroidDataDirs();
753 * Generates the raw path to an application's data
756 public static File[] buildExternalStorageAppDataDirs(String packageName) {
757 throwIfUserRequired();
758 return sCurrentUser.buildExternalStorageAppDataDirs(packageName);
762 * Generates the raw path to an application's media
765 public static File[] buildExternalStorageAppMediaDirs(String packageName) {
766 throwIfUserRequired();
767 return sCurrentUser.buildExternalStorageAppMediaDirs(packageName);
771 * Generates the raw path to an application's OBB files
774 public static File[] buildExternalStorageAppObbDirs(String packageName) {
775 throwIfUserRequired();
776 return sCurrentUser.buildExternalStorageAppObbDirs(packageName);
780 * Generates the path to an application's files.
783 public static File[] buildExternalStorageAppFilesDirs(String packageName) {
784 throwIfUserRequired();
785 return sCurrentUser.buildExternalStorageAppFilesDirs(packageName);
789 * Generates the path to an application's cache.
792 public static File[] buildExternalStorageAppCacheDirs(String packageName) {
793 throwIfUserRequired();
794 return sCurrentUser.buildExternalStorageAppCacheDirs(packageName);
798 * Return the download/cache content directory.
800 public static File getDownloadCacheDirectory() {
801 return DIR_DOWNLOAD_CACHE;
805 * Unknown storage state, such as when a path isn't backed by known storage
808 * @see #getExternalStorageState(File)
810 public static final String MEDIA_UNKNOWN = "unknown";
813 * Storage state if the media is not present.
815 * @see #getExternalStorageState(File)
817 public static final String MEDIA_REMOVED = "removed";
820 * Storage state if the media is present but not mounted.
822 * @see #getExternalStorageState(File)
824 public static final String MEDIA_UNMOUNTED = "unmounted";
827 * Storage state if the media is present and being disk-checked.
829 * @see #getExternalStorageState(File)
831 public static final String MEDIA_CHECKING = "checking";
834 * Storage state if the media is present but is blank or is using an
835 * unsupported filesystem.
837 * @see #getExternalStorageState(File)
839 public static final String MEDIA_NOFS = "nofs";
842 * Storage state if the media is present and mounted at its mount point with
845 * @see #getExternalStorageState(File)
847 public static final String MEDIA_MOUNTED = "mounted";
850 * Storage state if the media is present and mounted at its mount point with
853 * @see #getExternalStorageState(File)
855 public static final String MEDIA_MOUNTED_READ_ONLY = "mounted_ro";
858 * Storage state if the media is present not mounted, and shared via USB
861 * @see #getExternalStorageState(File)
863 public static final String MEDIA_SHARED = "shared";
866 * Storage state if the media was removed before it was unmounted.
868 * @see #getExternalStorageState(File)
870 public static final String MEDIA_BAD_REMOVAL = "bad_removal";
873 * Storage state if the media is present but cannot be mounted. Typically
874 * this happens if the file system on the media is corrupted.
876 * @see #getExternalStorageState(File)
878 public static final String MEDIA_UNMOUNTABLE = "unmountable";
881 * Storage state if the media is in the process of being ejected.
883 * @see #getExternalStorageState(File)
885 public static final String MEDIA_EJECTING = "ejecting";
888 * Returns the current state of the primary shared/external storage media.
890 * @see #getExternalStorageDirectory()
891 * @return one of {@link #MEDIA_UNKNOWN}, {@link #MEDIA_REMOVED},
892 * {@link #MEDIA_UNMOUNTED}, {@link #MEDIA_CHECKING},
893 * {@link #MEDIA_NOFS}, {@link #MEDIA_MOUNTED},
894 * {@link #MEDIA_MOUNTED_READ_ONLY}, {@link #MEDIA_SHARED},
895 * {@link #MEDIA_BAD_REMOVAL}, or {@link #MEDIA_UNMOUNTABLE}.
897 public static String getExternalStorageState() {
898 final File externalDir = sCurrentUser.getExternalDirs()[0];
899 return getExternalStorageState(externalDir);
903 * @deprecated use {@link #getExternalStorageState(File)}
906 public static String getStorageState(File path) {
907 return getExternalStorageState(path);
911 * Returns the current state of the shared/external storage media at the
914 * @return one of {@link #MEDIA_UNKNOWN}, {@link #MEDIA_REMOVED},
915 * {@link #MEDIA_UNMOUNTED}, {@link #MEDIA_CHECKING},
916 * {@link #MEDIA_NOFS}, {@link #MEDIA_MOUNTED},
917 * {@link #MEDIA_MOUNTED_READ_ONLY}, {@link #MEDIA_SHARED},
918 * {@link #MEDIA_BAD_REMOVAL}, or {@link #MEDIA_UNMOUNTABLE}.
920 public static String getExternalStorageState(File path) {
921 final StorageVolume volume = StorageManager.getStorageVolume(path, UserHandle.myUserId());
922 if (volume != null) {
923 return volume.getState();
925 return MEDIA_UNKNOWN;
930 * Returns whether the primary shared/external storage media is physically
933 * @return true if the storage device can be removed (such as an SD card),
934 * or false if the storage device is built in and cannot be
935 * physically removed.
937 public static boolean isExternalStorageRemovable() {
938 final File externalDir = sCurrentUser.getExternalDirs()[0];
939 return isExternalStorageRemovable(externalDir);
943 * Returns whether the shared/external storage media at the given path is
944 * physically removable.
946 * @return true if the storage device can be removed (such as an SD card),
947 * or false if the storage device is built in and cannot be
948 * physically removed.
949 * @throws IllegalArgumentException if the path is not a valid storage
952 public static boolean isExternalStorageRemovable(File path) {
953 final StorageVolume volume = StorageManager.getStorageVolume(path, UserHandle.myUserId());
954 if (volume != null) {
955 return volume.isRemovable();
957 throw new IllegalArgumentException("Failed to find storage device at " + path);
962 * Returns whether the primary shared/external storage media is emulated.
964 * The contents of emulated storage devices are backed by a private user
965 * data partition, which means there is little benefit to apps storing data
966 * here instead of the private directories returned by
967 * {@link Context#getFilesDir()}, etc.
969 * This returns true when emulated storage is backed by either internal
970 * storage or an adopted storage device.
972 * @see DevicePolicyManager#setStorageEncryption(android.content.ComponentName,
975 public static boolean isExternalStorageEmulated() {
976 final File externalDir = sCurrentUser.getExternalDirs()[0];
977 return isExternalStorageEmulated(externalDir);
981 * Returns whether the shared/external storage media at the given path is
984 * The contents of emulated storage devices are backed by a private user
985 * data partition, which means there is little benefit to apps storing data
986 * here instead of the private directories returned by
987 * {@link Context#getFilesDir()}, etc.
989 * This returns true when emulated storage is backed by either internal
990 * storage or an adopted storage device.
992 * @throws IllegalArgumentException if the path is not a valid storage
995 public static boolean isExternalStorageEmulated(File path) {
996 final StorageVolume volume = StorageManager.getStorageVolume(path, UserHandle.myUserId());
997 if (volume != null) {
998 return volume.isEmulated();
1000 throw new IllegalArgumentException("Failed to find storage device at " + path);
1004 static File getDirectory(String variableName, String defaultPath) {
1005 String path = System.getenv(variableName);
1006 return path == null ? new File(defaultPath) : new File(path);
1010 public static void setUserRequired(boolean userRequired) {
1011 sUserRequired = userRequired;
1014 private static void throwIfUserRequired() {
1015 if (sUserRequired) {
1016 Log.wtf(TAG, "Path requests must specify a user by using UserEnvironment",
1022 * Append path segments to each given base path, returning result.
1026 public static File[] buildPaths(File[] base, String... segments) {
1027 File[] result = new File[base.length];
1028 for (int i = 0; i < base.length; i++) {
1029 result[i] = buildPath(base[i], segments);
1035 * Append path segments to given base path, returning result.
1040 public static File buildPath(File base, String... segments) {
1042 for (String segment : segments) {
1044 cur = new File(segment);
1046 cur = new File(cur, segment);
1054 * If the given path exists on emulated external storage, return the
1055 * translated backing path hosted on internal storage. This bypasses any
1056 * emulation later, improving performance. This is <em>only</em> suitable
1057 * for read-only access.
1059 * Returns original path if given path doesn't meet these criteria. Callers
1060 * must hold {@link android.Manifest.permission#WRITE_MEDIA_STORAGE}
1065 public static File maybeTranslateEmulatedPathToInternal(File path) {
1066 return StorageManager.maybeTranslateEmulatedPathToInternal(path);