Java Code Examples for android.support.v4.content.ContextCompat#getExternalFilesDirs()

The following examples show how to use android.support.v4.content.ContextCompat#getExternalFilesDirs() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MemoryStorage.java    From carstream-android-auto with Apache License 2.0 6 votes vote down vote up
public static String[] getStorageDirectories(Context pContext)
{
    // Final set of paths
    final Set<String> rv = new HashSet<>();

    //Get primary & secondary external device storage (internal storage & micro SDCARD slot...)
    File[]  listExternalDirs = ContextCompat.getExternalFilesDirs(pContext, null);
    for(int i=0;i<listExternalDirs.length;i++){
        if(listExternalDirs[i] != null) {
            String path = listExternalDirs[i].getAbsolutePath();
            int indexMountRoot = path.indexOf("/Android/data/");
            if(indexMountRoot >= 0 && indexMountRoot <= path.length()){
                //Get the root path for the external directory
                rv.add(path.substring(0, indexMountRoot));
            }
        }
    }
    return rv.toArray(new String[rv.size()]);
}
 
Example 2
Source File: ContextUtils.java    From memetastic with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Get public (accessible) appdata folders
 */
@SuppressWarnings("StatementWithEmptyBody")
public List<Pair<File, String>> getAppDataPublicDirs(boolean internalStorageFolder, boolean sdcardFolders, boolean storageNameWithoutType) {
    List<Pair<File, String>> dirs = new ArrayList<>();
    for (File externalFileDir : ContextCompat.getExternalFilesDirs(_context, null)) {
        if (externalFileDir == null || Environment.getExternalStorageDirectory() == null) {
            continue;
        }
        boolean isInt = externalFileDir.getAbsolutePath().startsWith(Environment.getExternalStorageDirectory().getAbsolutePath());
        boolean add = (internalStorageFolder && isInt) || (sdcardFolders && !isInt);
        if (add) {
            dirs.add(new Pair<>(externalFileDir, getStorageName(externalFileDir, storageNameWithoutType)));
            if (!externalFileDir.exists() && externalFileDir.mkdirs()) ;
        }
    }
    return dirs;
}
 
Example 3
Source File: ContextUtils.java    From openlauncher with Apache License 2.0 6 votes vote down vote up
/**
 * Get public (accessible) appdata folders
 */
@SuppressWarnings("StatementWithEmptyBody")
public List<Pair<File, String>> getAppDataPublicDirs(boolean internalStorageFolder, boolean sdcardFolders, boolean storageNameWithoutType) {
    List<Pair<File, String>> dirs = new ArrayList<>();
    for (File externalFileDir : ContextCompat.getExternalFilesDirs(_context, null)) {
        if (externalFileDir == null || Environment.getExternalStorageDirectory() == null) {
            continue;
        }
        boolean isInt = externalFileDir.getAbsolutePath().startsWith(Environment.getExternalStorageDirectory().getAbsolutePath());
        boolean add = (internalStorageFolder && isInt) || (sdcardFolders && !isInt);
        if (add) {
            dirs.add(new Pair<>(externalFileDir, getStorageName(externalFileDir, storageNameWithoutType)));
            if (!externalFileDir.exists() && externalFileDir.mkdirs()) ;
        }
    }
    return dirs;
}
 
Example 4
Source File: FolderChooser.java    From screenrecorder with GNU Affero General Public License v3.0 6 votes vote down vote up
private void initialize() {
    setPersistent(true);
    setDialogTitle(null);
    setDialogLayoutResource(R.layout.director_chooser);
    setPositiveButtonText(android.R.string.ok);
    setNegativeButtonText(android.R.string.cancel);
    currentDir = new File(Environment.getExternalStorageDirectory() + File.separator + Const.APPDIR);
    setSummary(getPersistedString(currentDir.getPath()));
    Log.d(Const.TAG, "Persisted String is: " + getPersistedString(currentDir.getPath()));
    File[] SDCards = ContextCompat.getExternalFilesDirs(getContext().getApplicationContext(), null);
    storages.add(new Storages(Environment.getExternalStorageDirectory().getPath(), Storages.StorageType.Internal));
    prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
    if (SDCards.length > 1)
        storages.add(new Storages(SDCards[1].getPath(), Storages.StorageType.External));
    //getRemovableSDPath(SDCards[1]);
}
 
Example 5
Source File: IOUtil.java    From droidddle with Apache License 2.0 6 votes vote down vote up
public static File getBestAvailableFilesRoot(Context context) {
    File[] roots = ContextCompat.getExternalFilesDirs(context, null);
    if (roots != null) {
        for (File root : roots) {
            if (root == null) {
                continue;
            }

            if (Environment.MEDIA_MOUNTED.equals(EnvironmentCompat.getStorageState(root))) {
                return root;
            }
        }
    }

    // Worst case, resort to internal storage
    return context.getFilesDir();
}
 
Example 6
Source File: ContextUtils.java    From kimai-android with MIT License 6 votes vote down vote up
/**
 * Get public (accessible) appdata folders
 */
@SuppressWarnings("StatementWithEmptyBody")
public List<Pair<File, String>> getAppDataPublicDirs(boolean internalStorageFolder, boolean sdcardFolders, boolean storageNameWithoutType) {
    List<Pair<File, String>> dirs = new ArrayList<>();
    for (File externalFileDir : ContextCompat.getExternalFilesDirs(_context, null)) {
        if (externalFileDir == null || Environment.getExternalStorageDirectory() == null) {
            continue;
        }
        boolean isInt = externalFileDir.getAbsolutePath().startsWith(Environment.getExternalStorageDirectory().getAbsolutePath());
        boolean add = (internalStorageFolder && isInt) || (sdcardFolders && !isInt);
        if (add) {
            dirs.add(new Pair<>(externalFileDir, getStorageName(externalFileDir, storageNameWithoutType)));
            if (!externalFileDir.exists() && externalFileDir.mkdirs()) ;
        }
    }
    return dirs;
}
 
Example 7
Source File: StorageUtils.java    From IndiaSatelliteWeather with GNU General Public License v2.0 6 votes vote down vote up
public static File getAppSpecificFolder() {
    Context context = WeatherApplication.getContext();
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        // External directory
        File[] files = ContextCompat.getExternalFilesDirs(context, null);

        for (File file : files) {
            if (file != null && file.exists() && file.canRead() && file.canWrite()) {
                return file;
            }
        }
        return context.getFilesDir();
    } else {
        // Internal directory
        return context.getFilesDir();
    }
}
 
Example 8
Source File: DefaultDirChooser.java    From Android-Remote with GNU General Public License v3.0 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.KITKAT)
private LinkedList<String> getDirectories() {
    LinkedList<String> directories = new LinkedList<>();

    File[] defaultDirs = ContextCompat.getExternalFilesDirs(mContext, Environment.DIRECTORY_MUSIC);
    for (File f : defaultDirs) {
        if (f != null)
            directories.add(f.toString());
    }

    String publicMusicDir = Environment
            .getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).toString();
    if (canWriteToExternalStorage(publicMusicDir)) {
        directories.add(publicMusicDir);
    }

    if (canWriteToExternalStorage(
            Environment.getExternalStorageDirectory().getAbsolutePath())) {
        directories.add(mContext.getString(R.string.file_dialog_custom_paths_available));
    }
    return directories;
}
 
Example 9
Source File: Utils.java    From PRDownloader with Apache License 2.0 5 votes vote down vote up
public static String getRootDirPath(Context context) {
    if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
        File file = ContextCompat.getExternalFilesDirs(context.getApplicationContext(),
                null)[0];
        return file.getAbsolutePath();
    } else {
        return context.getApplicationContext().getFilesDir().getAbsolutePath();
    }
}
 
Example 10
Source File: StoreUtils.java    From letv with Apache License 2.0 5 votes vote down vote up
public static String getVer4_4DownloadPath(Context context) {
    File[] dirs = ContextCompat.getExternalFilesDirs(context, null);
    LogInfo.log("ljnalex", "dirs.length:" + dirs.length);
    if (dirs == null || dirs.length == 0) {
        return "";
    }
    if (isSdcardAvailable() && dirs.length >= 2 && dirs[1] != null) {
        return dirs[1].getAbsolutePath();
    }
    if (isSdcardAvailable() || dirs[0] == null) {
        return "";
    }
    return dirs[0].getAbsolutePath();
}
 
Example 11
Source File: DeviceState.java    From product-emm with Apache License 2.0 5 votes vote down vote up
public DeviceState(Context context) {
    this.context = context;
    this.info = new DeviceInfo(context);
    this.dataDirectory = new File(context.getFilesDir().getAbsoluteFile().toString());
    if (externalMemoryAvailable()) {
        this.externalStorageDirectoryList = ContextCompat.getExternalFilesDirs(context, null);
    }
}
 
Example 12
Source File: ContextUtil.java    From PowerFileExplorer with GNU General Public License v3.0 4 votes vote down vote up
public static File[] getExternalFilesDirs(String type) {
    return ContextCompat.getExternalFilesDirs(Base.getContext(), type);
}
 
Example 13
Source File: StorageUtils.java    From IslamicLibraryAndroid with GNU General Public License v3.0 4 votes vote down vote up
/**
 * @return A List of all storage locations available
 */
@NonNull
public static List<Storage> getAllStorageLocations(@NonNull Context context) {

/*
  This first condition is the code moving forward, since the else case is a bunch
  of unsupported hacks.

  For Kitkat and above, we rely on Environment.getExternalFilesDirs to give us a list
  of application writable directories (none of which require WRITE_EXTERNAL_STORAGE on
  Kitkat and above).

  Previously, we only would show anything if there were at least 2 entries. For M,
  some changes were made, such that on M, we even show this if there is only one
  entry.

  Irrespective of whether we require 1 entry (M) or 2 (Kitkat and L), we add an
  additional entry explicitly for the sdcard itself, (the one requiring
  WRITE_EXTERNAL_STORAGE to write).

  Thus, on Kitkat, the user may either:
  a. not see any item (if there's only one entry returned by getExternalFilesDirs, we won't
  show any options since it's the same sdcard and we have the permission and the user can't
  revoke it pre-Kitkat), or
  b. see 3+ items - /sdcard, and then at least 2 external fiels directories.

  on M, the user will always see at least 2 items (the external files dir and the actual
  external storage directory), and potentially more (depending on how many items are returned
  by getExternalFilesDirs).
 */
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        List<Storage> result = new ArrayList<>();
        int limit = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ? 1 : 2;
        final File[] mountPoints = ContextCompat.getExternalFilesDirs(context, null);
        if (mountPoints != null && mountPoints.length >= limit) {
            int typeId;
            if (!Environment.isExternalStorageRemovable() || Environment.isExternalStorageEmulated()) {
                typeId = R.string.prefs_sdcard_internal;
            } else {
                typeId = R.string.prefs_sdcard_external;
            }

            int number = 1;
            result.add(new Storage(context.getString(typeId, number),
                    Environment.getExternalStorageDirectory().getAbsolutePath(),
                    Build.VERSION.SDK_INT >= Build.VERSION_CODES.M));
            for (File mountPoint : mountPoints) {
                if (mountPoint != null) {
                    result.add(new Storage(context.getString(typeId, number++),
                            mountPoint.getAbsolutePath()));
                    typeId = R.string.prefs_sdcard_external;
                }
            }
        }
        return result;
    } else {
        return getLegacyStorageLocations(context);
    }
}
 
Example 14
Source File: FontPreferenceCompat.java    From memetastic with GNU General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("ResultOfMethodCallIgnored")
public List<File> getAdditionalFonts() {
    final ArrayList<File> additionalFonts = new ArrayList<>();

    // Bundled fonts
    try {
        //noinspection ConstantConditions
        for (String filename : getContext().getAssets().list("fonts")) {
            additionalFonts.add(new File(ANDROID_ASSET_DIR + "fonts", filename));
        }
    } catch (Exception ignored) {
    }

    // Directories that are additionally checked out for fonts
    final List<File> checkedDirs = new ArrayList<>(Arrays.asList(
            new File(getContext().getFilesDir(), ".app/fonts"),
            new File(getContext().getFilesDir(), ".app/Fonts"),
            additionalyCheckedFolder,
            new File(Environment.getExternalStorageDirectory(), "fonts"),
            new File(Environment.getExternalStorageDirectory(), "Fonts")
    ));

    // Also check external storage directories, at the respective root and data directory
    for (File externalFileDir : ContextCompat.getExternalFilesDirs(getContext(), null)) {
        if (externalFileDir == null || externalFileDir.getAbsolutePath() == null) {
            continue;
        }
        checkedDirs.add(new File(externalFileDir.getAbsolutePath().replaceFirst("/Android/data/.*$", "/fonts")));
        checkedDirs.add(new File(externalFileDir.getAbsolutePath().replaceFirst("/Android/data/.*$", "/Fonts")));
        checkedDirs.add(new File(externalFileDir.getAbsolutePath(), "/fonts"));
        checkedDirs.add(new File(externalFileDir.getAbsolutePath(), "/Fonts"));
    }
    // Check all directories for fonts
    for (File checkedDir : checkedDirs) {
        if (checkedDir != null && checkedDir.exists()) {
            File[] checkedDirFiles = checkedDir.listFiles(FONT_FILENAME_FILTER);
            if (checkedDirFiles != null) {
                for (File font : checkedDirFiles) {
                    if (!additionalFonts.contains(new File(font.getAbsolutePath().replace("/Fonts/", "/fonts/")))) {
                        additionalFonts.add(font);
                    }
                }
            }
        }
    }

    return additionalFonts;
}