Java Code Examples for android.content.Context#getExternalFilesDirs()

The following examples show how to use android.content.Context#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: FileUtil.java    From commcare-android with Apache License 2.0 6 votes vote down vote up
@SuppressLint("NewApi")
private static String getExternalDirectoryKitKat(Context c) {
    File[] extMounts = c.getExternalFilesDirs(null);
    // first entry is emualted storage. Second if it exists is secondary (real) SD.

    if (extMounts.length < 2) {
        return null;
    }

    /*
     * First volume returned by getExternalFilesDirs is always "primary" volume,
     * or emulated. Further entries, if they exist, will be "secondary" or external SD
     *
     * http://www.doubleencore.com/2014/03/android-external-storage/
     *
     */

    File sdRoot = extMounts[1];

    // because apparently getExternalFilesDirs entries can be null
    if (sdRoot == null) {
        return null;
    }

    return sdRoot.getAbsolutePath() + "/Android/data/org.commcare.dalvik";
}
 
Example 2
Source File: StorageUtil.java    From Camera-Roll-Android-App with Apache License 2.0 6 votes vote down vote up
public static File[] getRemovableStorageRoots(Context context) {
    File[] roots = context.getExternalFilesDirs("external");
    ArrayList<File> rootsArrayList = new ArrayList<>();

    for (int i = 0; i < roots.length; i++) {
        if (roots[i] != null) {
            String path = roots[i].getPath();
            int index = path.lastIndexOf("/Android/data/");
            if (index > 0) {
                path = path.substring(0, index);
                if (!path.equals(Environment.getExternalStorageDirectory().getPath())) {
                    rootsArrayList.add(new File(path));
                }
            }
        }
    }

    roots = new File[rootsArrayList.size()];
    rootsArrayList.toArray(roots);
    return roots;
}
 
Example 3
Source File: FileUtil.java    From PowerFileExplorer with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Get a list of external SD card paths. (Kitkat or higher.)
 *
 * @return A list of external SD card paths.
 */
@TargetApi(Build.VERSION_CODES.KITKAT)
private static String[] getExtSdCardPaths(Context context) {
    List<String> paths = new ArrayList<>();
    for (File file : context.getExternalFilesDirs("external")) {
        if (file != null && !file.equals(context.getExternalFilesDir("external"))) {
            int index = file.getAbsolutePath().lastIndexOf("/Android/data");
            if (index < 0) {
                Log.w("AmazeFileUtils", "Unexpected external file dir: " + file.getAbsolutePath());
            } else {
                String path = file.getAbsolutePath().substring(0, index);
                try {
                    path = new File(path).getCanonicalPath();
                } catch (IOException e) {
                    // Keep non-canonical path.
                }
                paths.add(path);
            }
        }
    }
    if (paths.isEmpty()) paths.add("/storage/sdcard1");
    return paths.toArray(new String[0]);
}
 
Example 4
Source File: FileUtil.java    From PowerFileExplorer with GNU General Public License v3.0 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.KITKAT)
public static String[] getExtSdCardPathsForActivity(Context context) {
    List<String> paths = new ArrayList<>();
    for (File file : context.getExternalFilesDirs("external")) {
        if (file != null) {
            int index = file.getAbsolutePath().lastIndexOf("/Android/data");
            if (index < 0) {
                Log.w("AmazeFileUtils", "Unexpected external file dir: " + file.getAbsolutePath());
            } else {
                String path = file.getAbsolutePath().substring(0, index);
                try {
                    path = new File(path).getCanonicalPath();
                } catch (IOException e) {
                    // Keep non-canonical path.
                }
                paths.add(path);
            }
        }
    }
    if (paths.isEmpty()) paths.add("/storage/sdcard1");
    return paths.toArray(new String[0]);
}
 
Example 5
Source File: AndroidPathUtils.java    From PowerFileExplorer with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Get a list of external SD card paths. (Kitkat or higher.)
 *
 * @return A list of external SD card paths.
 */
@TargetApi(Build.VERSION_CODES.KITKAT)
private static String[] getExtSdCardPaths(final Context c) {
	List<String> paths = new ArrayList<String>();
	for (File file : c.getExternalFilesDirs("external")) {
		if (file != null && !file.equals(c.getExternalFilesDir("external"))) {
			int index = file.getAbsolutePath().lastIndexOf("/Android/data");
			if (index < 0) {
				Log.w("Uri", "Unexpected external file dir: " + file.getAbsolutePath());
			} else {
				String path = file.getAbsolutePath().substring(0, index);
				try {
					path = new File(path).getCanonicalPath();
				} catch (IOException e) {
					// Keep non-canonical path.
				}
				paths.add(path);
			}
		}
	}
	return paths.toArray(new String[paths.size()]);
}
 
Example 6
Source File: FileUtil.java    From PowerFileExplorer with GNU General Public License v3.0 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.KITKAT)
 public static String[] getExtSdCardPathsForActivity(Context context) {
     List<String> paths = new ArrayList<>();
     for (File file : context.getExternalFilesDirs("external")) {
         Log.d(TAG, "external: " + file.getAbsolutePath());
if (file != null) {
             int index = file.getAbsolutePath().lastIndexOf("/Android/data");
             if (index < 0) {
                 Log.w("AmazeFileUtils", "Unexpected external file dir: " + file.getAbsolutePath());
             } else {
                 String path = file.getAbsolutePath().substring(0, index);
                 try {
                     path = new File(path).getCanonicalPath();
                 } catch (IOException e) {
                     // Keep non-canonical path.
                 }
                 paths.add(path);
             }
         }
     }
     if (paths.isEmpty()) 
paths.add("/storage/sdcard1");
     return paths.toArray(new String[0]);
 }
 
Example 7
Source File: ExternalFileUtils.java    From prevent with Do What The F*ck You Want To Public License 5 votes vote down vote up
public static File[] getExternalFilesDirs(Context context) {
    File[] files;
    files = context.getExternalFilesDirs(null);
    if (files == null) {
        files = new File[0];
    }
    return files;
}
 
Example 8
Source File: FileUtil.java    From edx-app-android with Apache License 2.0 5 votes vote down vote up
/**
 * Utility method to get the removable storage directory (such as SD-Card).
 *
 * @param context The current context.
 * @return Return removable storage directory if available otherwise null.
 */
@Nullable
public static File getRemovableStorageAppDir(@NonNull Context context) {
    final int currentApiVersion = android.os.Build.VERSION.SDK_INT;
    if (currentApiVersion >= Build.VERSION_CODES.LOLLIPOP) {
        final File[] fileList = context.getExternalFilesDirs(null);
        for (File extFile : fileList) {
            if (extFile != null && Environment.isExternalStorageRemovable(extFile)) {
                return extFile;
            }
        }
    }
    return null;
}
 
Example 9
Source File: FileProvider.java    From AndPermission with Apache License 2.0 5 votes vote down vote up
private static File[] getExternalFilesDirs(Context context, String type) {
    if (Build.VERSION.SDK_INT >= 19) {
        return context.getExternalFilesDirs(type);
    } else {
        return new File[] {context.getExternalFilesDir(type)};
    }
}
 
Example 10
Source File: CompatUtils.java    From microMathematics with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Procedure retrieves the storage directory
 */
public static String[] getStorageDirs(Context ctx)
{
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
    {
        File[] ff = ctx.getExternalFilesDirs(null);
        if (ff == null)
            return null;
        String[] res = new String[ff.length];
        for (int i = 0; i < ff.length; i++)
        {
            if (ff[i] == null)
                continue;
            String path = ff[i].getAbsolutePath();
            if (path == null)
                continue;
            int pos = path.indexOf("Android");
            if (pos < 0)
            {
                continue;
            }
            res[i] = path.substring(0, pos);
        }
        return res;
    }
    else
    {
        return null;
    }
}
 
Example 11
Source File: StorageHelper.java    From leafpicrevived with GNU General Public License v3.0 5 votes vote down vote up
public static HashSet<File> getStorageRoots(Context context) {
    HashSet<File> paths = new HashSet<File>();
    for (File file : context.getExternalFilesDirs("external")) {
        if (file != null) {
            int index = file.getAbsolutePath().lastIndexOf("/Android/data");
            if (index < 0)
                Log.w("asd", "Unexpected external file dir: " + file.getAbsolutePath());
            else
                paths.add(new File(file.getAbsolutePath().substring(0, index)));
        }
    }
    return paths;
}
 
Example 12
Source File: Framework.java    From atlas with Apache License 2.0 5 votes vote down vote up
public static File[] getExternalFilesDirs(Context context, String type) {
    final int version = Build.VERSION.SDK_INT;
    if (version >= 19) {
        //返回结果可能存在null值
        return context.getExternalFilesDirs(type);
    } else {
        return new File[] { context.getExternalFilesDir(type) };
    }
}
 
Example 13
Source File: Global.java    From NClientV2 with Apache License 2.0 5 votes vote down vote up
public static List<File>getUsableFolders(Context context){
    List<File>strings=new ArrayList<>();
    if(Build.VERSION.SDK_INT<Build.VERSION_CODES.Q)
        strings.add(Environment.getExternalStorageDirectory());

    if(Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT)
        return strings;

    File[]files=context.getExternalFilesDirs(null);
    strings.addAll(Arrays.asList(files));
    return strings;
}
 
Example 14
Source File: StorageUtils.java    From osmdroid with Apache License 2.0 5 votes vote down vote up
@SuppressLint("NewApi")
private static List<StorageInfo> getStorageListApi19(Context context) {
    ArrayList<StorageInfo> storageInfos = new ArrayList<>();

    storageInfos.add(new StorageInfo(context.getFilesDir().getAbsolutePath(), true, false, -1));

    ArrayList<File> storageDirs = new ArrayList<>();
    File[] externalDirs = context.getExternalFilesDirs( null);

    for (File externalDir : externalDirs) {
        // "Returned paths may be null if a storage device is unavailable."
        if (externalDir == null) {
            continue;
        }

        String state = Environment.getStorageState(externalDir);
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            storageDirs.add(externalDir);
        }
    }

    for (File storageDir : storageDirs) {
        storageInfos.add(new StorageInfo(storageDir.getAbsolutePath(), false, false, -1));
    }

    return storageInfos;
}
 
Example 15
Source File: StorageHelper.java    From leafpicrevived with GNU General Public License v3.0 5 votes vote down vote up
public static String getSdcardPath(Context context) {
    for (File file : context.getExternalFilesDirs("external")) {
        if (file != null && !file.equals(context.getExternalFilesDir("external"))) {
            int index = file.getAbsolutePath().lastIndexOf("/Android/data");
            if (index < 0)
                Log.w("asd", "Unexpected external file dir: " + file.getAbsolutePath());
            else
                return new File(file.getAbsolutePath().substring(0, index)).getPath();
        }
    }
    return null;
}
 
Example 16
Source File: Paths.java    From YalpStore with GNU General Public License v2.0 4 votes vote down vote up
static private File[] getExternalFilesDirs(Context context) {
    return Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
        ? context.getExternalFilesDirs(null)
        : new File[] {new File(Environment.getExternalStorageDirectory(), FALLBACK_DIRECTORY)}
    ;
}
 
Example 17
Source File: FileProvider.java    From attach with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Parse and return {@link PathStrategy} for given authority as defined in
 * {@link #META_DATA_FILE_PROVIDER_PATHS} {@code <meta-data>}.
 *
 * @see #getPathStrategy(Context, String)
 */
private static PathStrategy parsePathStrategy(Context context, String authority)
        throws IOException, XmlPullParserException {
    final SimplePathStrategy strat = new SimplePathStrategy(authority);

    final ProviderInfo info = context.getPackageManager()
            .resolveContentProvider(authority, PackageManager.GET_META_DATA);
    final XmlResourceParser in = info.loadXmlMetaData(
            context.getPackageManager(), META_DATA_FILE_PROVIDER_PATHS);
    if (in == null) {
        throw new IllegalArgumentException(
                "Missing " + META_DATA_FILE_PROVIDER_PATHS + " meta-data");
    }

    int type;
    while ((type = in.next()) != END_DOCUMENT) {
        if (type == START_TAG) {
            final String tag = in.getName();

            final String name = in.getAttributeValue(null, ATTR_NAME);
            String path = in.getAttributeValue(null, ATTR_PATH);

            File target = null;
            if (TAG_ROOT_PATH.equals(tag)) {
                target = DEVICE_ROOT;
            } else if (TAG_FILES_PATH.equals(tag)) {
                target = context.getFilesDir();
            } else if (TAG_CACHE_PATH.equals(tag)) {
                target = context.getCacheDir();
            } else if (TAG_EXTERNAL.equals(tag)) {
                target = Environment.getExternalStorageDirectory();
            } else if (TAG_EXTERNAL_FILES.equals(tag)) {
                File[] externalFilesDirs;
                if (Build.VERSION.SDK_INT >= 19) {
                    externalFilesDirs = context.getExternalFilesDirs(null);
                } else {
                    externalFilesDirs = new File[] { context.getExternalFilesDir(null) };
                }
                if (externalFilesDirs.length > 0) {
                    target = externalFilesDirs[0];
                }
            } else if (TAG_EXTERNAL_CACHE.equals(tag)) {
                File[] externalCacheDirs;
                if (Build.VERSION.SDK_INT >= 19) {
                    externalCacheDirs = context.getExternalCacheDirs();
                } else {
                    externalCacheDirs = new File[] { context.getExternalCacheDir() };
                }
                if (externalCacheDirs.length > 0) {
                    target = externalCacheDirs[0];
                }
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP
                    && TAG_EXTERNAL_MEDIA.equals(tag)) {
                File[] externalMediaDirs = context.getExternalMediaDirs();
                if (externalMediaDirs.length > 0) {
                    target = externalMediaDirs[0];
                }
            }

            if (target != null) {
                strat.addRoot(name, buildPath(target, path));
            }
        }
    }

    return strat;
}
 
Example 18
Source File: ContextCompatKitKat.java    From adt-leanback-support with Apache License 2.0 4 votes vote down vote up
public static File[] getExternalFilesDirs(Context context, String type) {
    return context.getExternalFilesDirs(type);
}
 
Example 19
Source File: ContextCompatKitKat.java    From guideshow with MIT License 4 votes vote down vote up
public static File[] getExternalFilesDirs(Context context, String type) {
    return context.getExternalFilesDirs(type);
}
 
Example 20
Source File: FileSelectionActivity.java    From Android-Multiple-file-Selector-Dialog with MIT License 4 votes vote down vote up
/**
 * Returns all available SD-Cards in the system (include emulated)
 * <p/>
 * Warning: Hack! Based on Android source code of version 4.3 (API 18)
 * Because there is no standard way to get it.
 * Edited by hendrawd
 *
 * @return paths to all available SD-Cards in the system (include emulated)
 */
public static String[] getStorageDirectories(Context context) {
    // Final set of paths
    final Set<String> rv = new HashSet<>();
    // Primary physical SD-CARD (not emulated)
    final String rawExternalStorage = System.getenv("EXTERNAL_STORAGE");
    // All Secondary SD-CARDs (all exclude primary) separated by ":"
    final String rawSecondaryStoragesStr = System.getenv("SECONDARY_STORAGE");
    // Primary emulated SD-CARD
    final String rawEmulatedStorageTarget = System.getenv("EMULATED_STORAGE_TARGET");
    if (TextUtils.isEmpty(rawEmulatedStorageTarget)) {
        //fix of empty raw emulated storage on marshmallow
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            File[] files = context.getExternalFilesDirs(null);
            for (File file : files) {
                String applicationSpecificAbsolutePath = file.getAbsolutePath();
                String emulatedRootPath = applicationSpecificAbsolutePath.substring(0, applicationSpecificAbsolutePath.indexOf("Android/data"));
                rv.add(emulatedRootPath);
            }
        } else {
            // Device has physical external storage; use plain paths.
            if (TextUtils.isEmpty(rawExternalStorage)) {
                // EXTERNAL_STORAGE undefined; falling back to default.
                rv.addAll(Arrays.asList(getPhysicalPaths()));
            } else {
                rv.add(rawExternalStorage);
            }
        }
    } else {
        // Device has emulated storage; external storage paths should have
        // userId burned into them.
        final String rawUserId;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
            rawUserId = "";
        } else {
            final String path = Environment.getExternalStorageDirectory().getAbsolutePath();
            final String[] folders = DIR_SEPORATOR.split(path);
            final String lastFolder = folders[folders.length - 1];
            boolean isDigit = false;
            try {
                Integer.valueOf(lastFolder);
                isDigit = true;
            } catch (NumberFormatException ignored) {
            }
            rawUserId = isDigit ? lastFolder : "";
        }
        // /storage/emulated/0[1,2,...]
        if (TextUtils.isEmpty(rawUserId)) {
            rv.add(rawEmulatedStorageTarget);
        } else {
            rv.add(rawEmulatedStorageTarget + File.separator + rawUserId);
        }
    }
    // Add all secondary storages
    if (!TextUtils.isEmpty(rawSecondaryStoragesStr)) {
        // All Secondary SD-CARDs splited into array
        final String[] rawSecondaryStorages = rawSecondaryStoragesStr.split(File.pathSeparator);
        Collections.addAll(rv, rawSecondaryStorages);
    }
    return rv.toArray(new String[rv.size()]);
}