Example usage for android.content Context getExternalFilesDir

List of usage examples for android.content Context getExternalFilesDir

Introduction

In this page you can find the example usage for android.content Context getExternalFilesDir.

Prototype

@Nullable
public abstract File getExternalFilesDir(@Nullable String type);

Source Link

Document

Returns the absolute path to the directory on the primary shared/external storage device where the application can place persistent files it owns.

Usage

From source file:org.mapsforge.map.android.util.AndroidSupportUtil.java

/**
 * Returns if it is required to ask for runtime permission for accessing a directory.
 * @param context the activity asking/*from w  w w  . j  a  v a  2s  . co m*/
 * @param directory the directory accessed
 * @return true if runtime permission must be asked for
 */
public static boolean runtimePermissionRequiredForReadExternalStorage(Context context, File directory) {
    if (runtimePermissionRequired(context, Manifest.permission.READ_EXTERNAL_STORAGE)) {
        try {
            String canonicalPath = directory.getCanonicalPath();
            // not sure if this covers all possibilities: file is freely accessible if it is in the application external cache or external files
            // dir or somewhere else (e.g. internal storage) but not in the general external storage.
            return canonicalPath.startsWith(Environment.getExternalStorageDirectory().getCanonicalPath())
                    && !canonicalPath.startsWith(context.getExternalCacheDir().getCanonicalPath())
                    && !canonicalPath.startsWith(context.getExternalFilesDir(null).getCanonicalPath());
        } catch (IOException e) {
            LOGGER.warning("Directory access exception " + directory.toString() + e.getMessage());
            return true; // ?? it probably means the file cannot be found
        }
    }
    return false;
}

From source file:it.feio.android.omninotes.utils.StorageManager.java

public static boolean deleteExternalStoragePrivateFile(Context mContext, String name) {
    boolean res = false;

    // Checks for external storage availability
    if (!checkStorage()) {
        Toast.makeText(mContext, mContext.getString(R.string.storage_not_available), Toast.LENGTH_SHORT).show();
        return res;
    }/*from   w  w w  .  j  av  a2s  .  co  m*/

    File file = new File(mContext.getExternalFilesDir(null), name);
    if (file != null) {
        file.delete();
        res = true;
    }

    return res;
}

From source file:com.dycody.android.idealnote.utils.StorageHelper.java

public static boolean deleteExternalStoragePrivateFile(Context mContext, String name) {
    boolean res = false;

    // Checks for external storage availability
    if (!checkStorage()) {
        Toast.makeText(mContext,//from ww w.j av a  2 s. co m
                mContext.getString(com.dycody.android.idealnote.R.string.storage_not_available),
                Toast.LENGTH_SHORT).show();
        return false;
    }

    File file = new File(mContext.getExternalFilesDir(null), name);
    file.delete();

    return true;
}

From source file:github.daneren2005.dsub.util.FileUtil.java

public static File getSubsonicDirectory(Context context) {
    return context.getExternalFilesDir(null);
}

From source file:org.dkf.jed2k.android.LollipopFileSystem.java

private static String[] getExtSdCardPaths(Context context) {
    List<String> paths = new ArrayList<>();
    File[] externals = ContextCompat.getExternalFilesDirs(context, "external");
    File external = context.getExternalFilesDir("external");
    for (int i = 0; i < externals.length; i++) {
        File file = externals[i];
        if (file != null && !file.equals(external)) {
            String absolutePath = file.getAbsolutePath();
            int index = absolutePath.lastIndexOf("/Android/data");
            if (index >= 0) {
                String path = absolutePath.substring(0, index);
                try {
                    path = new File(path).getCanonicalPath();
                } catch (IOException e) {
                    // Keep non-canonical path.
                }//from  ww w.  ja v  a 2  s . c  o  m
                paths.add(path);
            } else {
                LOG.warn("ext sd card path wrong: {}", absolutePath);
            }
        }
    }
    // special hard coded paths for more security
    for (String path : FIXED_SDCARD_PATHS) {
        if (!paths.contains(path)) {
            paths.add(path);
        }
    }

    return paths.toArray(new String[0]);
}

From source file:com.frostwire.android.LollipopFileSystem.java

private static String[] getExtSdCardPaths(Context context) {
    List<String> paths = new ArrayList<>();
    File[] externals = ContextCompat.getExternalFilesDirs(context, "external");
    File external = context.getExternalFilesDir("external");
    for (File file : externals) {
        if (file != null && !file.equals(external)) {
            String absolutePath = file.getAbsolutePath();
            int index = absolutePath.lastIndexOf("/Android/data");
            if (index >= 0) {
                String path = absolutePath.substring(0, index);
                try {
                    path = new File(path).getCanonicalPath();
                } catch (IOException e) {
                    // Keep non-canonical path.
                }//from ww w.  j ava 2s  .c  o  m
                paths.add(path);
            } else {
                LOG.warn("ext sd card path wrong: " + absolutePath);
            }
        }
    }
    // special hard coded paths for more security
    for (String path : FIXED_SDCARD_PATHS) {
        if (!paths.contains(path)) {
            paths.add(path);
        }
    }

    return paths.toArray(new String[0]);
}

From source file:com.filemanager.free.filesystem.FileUtil.java

/**
 * Get a temp file.//from  w  w  w.  j av  a2 s. co m
 *
 * @param file The base file for which to create a temp file.
 * @return The temp file.
 */
public static final File getTempFile(@NonNull final File file, Context context) {
    File extDir = context.getExternalFilesDir(null);
    File tempFile = new File(extDir, file.getName());
    return tempFile;
}

From source file:com.filemanager.free.filesystem.FileUtil.java

/**
 * Copy a resource file into a private target directory, if the target does not yet exist. Required for the Kitkat
 * workaround./*  ww w  . j  av  a  2  s.  c om*/
 *
 * @param resource   The resource file.
 * @param folderName The folder below app folder where the file is copied to.
 * @param targetName The name of the target file.
 * @return the dummy file.
 * @throws IOException
 */
private static File copyDummyFile(final int resource, final String folderName, final String targetName,
        Context context) throws IOException {
    File externalFilesDir = context.getExternalFilesDir(folderName);
    if (externalFilesDir == null) {
        return null;
    }
    File targetFile = new File(externalFilesDir, targetName);

    if (!targetFile.exists()) {
        InputStream in = null;
        OutputStream out = null;
        try {
            in = context.getResources().openRawResource(resource);
            out = new FileOutputStream(targetFile);
            byte[] buffer = new byte[4096]; // MAGIC_NUMBER
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException ex) {
                    // do nothing
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException ex) {
                    // do nothing
                }
            }
        }
    }
    return targetFile;
}

From source file:com.androidzeitgeist.dashwatch.common.IOUtil.java

@TargetApi(Build.VERSION_CODES.KITKAT)
public static File getBestAvailableFilesRoot(Context context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        // In KitKat we can query multiple devices.
        // TODO: optimize for stability instead of picking first one
        File[] roots = context.getExternalFilesDirs(null);
        if (roots != null) {
            for (File root : roots) {
                if (root == null) {
                    continue;
                }/*from  ww  w .j a  va2s.c o  m*/

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

    } else if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
        // Pre-KitKat, only one external storage device was addressable
        return context.getExternalFilesDir(null);
    }

    // Worst case, resort to internal storage
    return context.getFilesDir();
}

From source file:com.github.piasy.rxqrcode.RxQrCode.java

public static Observable<File> generateQrCodeFile(Context context, String content, int width, int height) {
    return Observable.fromEmitter(emitter -> {
        MultiFormatWriter writer = new MultiFormatWriter();
        Bitmap origin = null;//from   w  w  w  .j  a v  a 2  s . c  o  m
        Bitmap scaled = null;
        try {
            BitMatrix bm = writer.encode(content, BarcodeFormat.QR_CODE, QR_CODE_LENGTH, QR_CODE_LENGTH,
                    Collections.singletonMap(EncodeHintType.MARGIN, 0));
            origin = Bitmap.createBitmap(QR_CODE_LENGTH, QR_CODE_LENGTH, Bitmap.Config.ARGB_8888);

            for (int i = 0; i < QR_CODE_LENGTH; i++) {
                for (int j = 0; j < QR_CODE_LENGTH; j++) {
                    origin.setPixel(i, j, bm.get(i, j) ? Color.BLACK : Color.WHITE);
                }
            }
            scaled = Bitmap.createScaledBitmap(origin, width, height, true);
            File dir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
            if (dir == null) {
                emitter.onError(new IllegalStateException("external file system unavailable!"));
                return;
            }
            String fileName = "rx_qr_" + System.currentTimeMillis() + ".png";
            File localFile = new File(dir, fileName);

            FileOutputStream outputStream = new FileOutputStream(localFile);
            scaled.compress(Bitmap.CompressFormat.PNG, 85, outputStream);
            outputStream.flush();
            outputStream.close();

            emitter.onNext(localFile);
            emitter.onCompleted();
        } catch (WriterException | IOException e) {
            emitter.onError(e);
        } finally {
            if (origin != null) {
                origin.recycle();
            }
            if (scaled != null) {
                scaled.recycle();
            }
        }
    }, Emitter.BackpressureMode.BUFFER);
}