Example usage for android.os Environment getExternalStorageState

List of usage examples for android.os Environment getExternalStorageState

Introduction

In this page you can find the example usage for android.os Environment getExternalStorageState.

Prototype

public static String getExternalStorageState() 

Source Link

Document

Returns the current state of the primary shared/external storage media.

Usage

From source file:Main.java

/**
 * Returns specified application cache directory. Cache directory will be created on SD card by defined path if card
 * is mounted and app has appropriate permission. Else - Android defines cache directory on device's file system.
 *
 * @param context  Application context//from   www  .ja  v  a  2 s .  com
 * @param cacheDir Cache directory path (e.g.: "AppCacheDir", "AppDir/cache/images")
 * @return Cache {@link File directory}
 */
public static File getOwnCacheDirectory(Context context, String cacheDir) {
    File appCacheDir = null;
    if (MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) && hasExternalStoragePermission(context)) {
        appCacheDir = new File(Environment.getExternalStorageDirectory(), cacheDir);
    }
    if (appCacheDir == null || (!appCacheDir.exists() && !appCacheDir.mkdirs())) {
        appCacheDir = context.getCacheDir();
    }
    return appCacheDir;
}

From source file:Main.java

/**
 * Returns application cache directory. Cache directory will be created on SD card
 * <i>("/Android/data/[app_package_name]/cache")</i> if card is mounted and app has appropriate permission. Else -
 * Android defines cache directory on device's file system.
 *
 * @param context Application context//  ww w.  j ava  2s.  co m
 * @return Cache {@link File directory}
 */
public static File getCacheDirectory(Context context) {
    File appCacheDir = null;
    if (MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) && hasExternalStoragePermission(context)) {
        appCacheDir = getExternalCacheDir(context);
    }
    if (appCacheDir == null) {
        appCacheDir = context.getCacheDir();
    }
    if (appCacheDir == null) {
        Log.w(TAG, "Can't define system cache directory! The app should be re-installed.");
    }
    return appCacheDir;
}

From source file:Main.java

public static boolean isCanUseSD() {
    try {//from w ww.  ja  v  a2s  .  c o m
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

From source file:ch.ethz.inf.vs.android.g54.a4.util.SnapshotCache.java

public static void storeSnapshot(List<WifiReading> readings, String fileName, Context c) {

    String state = Environment.getExternalStorageState();

    if (Environment.MEDIA_MOUNTED.equals(state)) {
        // We can read and write the external storage
        try {// w w  w.j  av a2 s .  c o  m
            JSONArray json = readingsToJson(readings);
            File root = c.getExternalCacheDir();
            File jsonFile = new File(root, constructFileName(fileName));
            FileOutputStream out;
            out = new FileOutputStream(jsonFile);
            out.write(json.toString().getBytes());
            out.close();
            U.showToast(constructFileName(fileName));
            Log.d(TAG, "Successfully stored snapshot to SDCard");
        } catch (Exception e) {
            U.showToast("Could not save the snapshot on the SDCard.");
            Log.e(TAG, "Could not save the snapshot on the SDCard.", e);
        }
    } else {
        U.showToast("Cannot write to external storage.");
    }
}

From source file:Main.java

/**
 * Returns a Java File initialized to a directory of given name
 * at the root storage location, with preference to external storage.
 * If the directory did not exist, it will be created at the conclusion of this call.
 * If a file with conflicting name exists, this method returns null;
 *
 * @param c the context to determine the internal storage location, if external is unavailable
 * @param directory_name the name of the directory desired at the storage location
 * @return a File pointing to the storage directory, or null if a file with conflicting name
 * exists/*from   www  . j a  va2  s .c o  m*/
 */
public static File getRootStorageDirectory(Context c, String directory_name) {
    File result;
    // First, try getting access to the sdcard partition
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        Log.d(TAG, "Using sdcard");
        result = new File(Environment.getExternalStorageDirectory(), directory_name);
    } else {
        // Else, use the internal storage directory for this application
        Log.d(TAG, "Using internal storage");
        result = new File(c.getApplicationContext().getFilesDir(), directory_name);
    }

    if (!result.exists())
        result.mkdir();
    else if (result.isFile()) {
        return null;
    }
    Log.d("getRootStorageDirectory", result.getAbsolutePath());
    return result;
}

From source file:Main.java

private static boolean createExternalStorageDirectory(File targetDir) {
    boolean dirCreated = false;
    if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
        if (targetDir != null) {
            if (!targetDir.mkdirs()) {
                if (targetDir.exists()) {
                    dirCreated = true;/*from   w  w w.j  a v a 2s . c  o m*/
                } else {
                    Log.d(targetDir.getName(), "Failed to create directory");
                    return false;
                }
            }
        }
    } else {
        Log.v(targetDir.getName(), "External storage is not mounted READ/WRITE.");
    }
    return dirCreated;
}

From source file:Main.java

public static void copyFolder(AssetManager assetManager, String source, String target) {
    // "Name" is the name of your folder!
    String[] files = null;/*  w  w  w  .  j  a v a 2  s . c o  m*/

    String state = Environment.getExternalStorageState();

    if (Environment.MEDIA_MOUNTED.equals(state)) {
        // We can read and write the media
        // Checking file on assets subfolder
        try {
            files = assetManager.list(source);
        } catch (IOException e) {
            Log.e("ERROR", "Failed to get asset file list.", e);
        }
        // Analyzing all file on assets subfolder
        for (String filename : files) {
            InputStream in = null;
            OutputStream out = null;
            // First: checking if there is already a target folder
            File folder = new File(target);
            boolean success = true;
            if (!folder.exists()) {
                success = folder.mkdir();
            }
            if (success) {
                // Moving all the files on external SD
                String sourceFile = source + "/" + filename;
                String targetFile = folder.getAbsolutePath() + "/" + filename;
                try {
                    in = assetManager.open(sourceFile);
                    out = new FileOutputStream(targetFile);
                    /*Log.i("WEBVIEW",
                      Environment.getExternalStorageDirectory()
                            + "/yourTargetFolder/" + name + "/"
                            + filename);*/
                    copyFile(in, out);
                    in.close();
                    in = null;
                    out.flush();
                    out.close();
                    out = null;
                } catch (IOException e) {
                    try {
                        assetManager.list(sourceFile);
                    } catch (IOException f) {
                        Log.e("ERROR", "Failed to copy asset file: " + filename, f);
                        continue;
                    }

                    copyFolder(assetManager, sourceFile, targetFile);
                }
            } else {
                // Do something else on failure
            }
        }
    } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        // We can only read the media
    } else {
        // Something else is wrong. It may be one of many other states, but
        // all we need
        // is to know is we can neither read nor write
    }
}

From source file:Main.java

public static File getOutputMediaFile(int type, int location) {

    // To be safe, you should check that the SDCard is mounted
    // using Environment.getExternalStorageState() before doing this.
    if (!Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED)) {
        return null;
    }//from  w  w w .j  a v a 2 s . c om

    File mediaStorageDir = (location == STORAGE_INT)
            ? new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                    STR_APP_NAME)
            : getActualExtSDCard(STR_APP_NAME);
    // This location works best if you want the created images to be shared
    // between applications and persist after your app has been uninstalled.

    // Create the storage directory if it does not exist
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.d(TAG, "failed to create directory");
            return null;
        }
    }

    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    File mediaFile;
    if (type == MEDIA_TYPE_IMAGE) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
    } else if (type == MEDIA_TYPE_VIDEO) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + "VID_" + timeStamp + ".mp4");
    } else {
        return null;
    }

    return mediaFile;
}

From source file:com.phonegap.DirectoryManager.java

/**
 * Get the free disk space on the SD card
 * // w w  w . ja v a 2s . co m
 * @return       Size in KB or -1 if not available
 */
protected static long getFreeDiskSpace() {
    String status = Environment.getExternalStorageState();
    long freeSpace = 0;

    // If SD card exists
    if (status.equals(Environment.MEDIA_MOUNTED)) {
        try {
            File path = Environment.getExternalStorageDirectory();
            StatFs stat = new StatFs(path.getPath());
            long blockSize = stat.getBlockSize();
            long availableBlocks = stat.getAvailableBlocks();
            freeSpace = availableBlocks * blockSize / 1024;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // If no SD card, then return -1
    else {
        return -1;
    }

    return (freeSpace);
}

From source file:ca.marcmeszaros.papyrus.tools.TNManager.java

/**
 * Downloads and saves the thumbnail of a book to the SD card.
 *
 * @param thumbnailURL the URL to the thumbnail
 * @param isbn the ISBN number of the book
 * @return {@code true} on success or {@code false} on failure
 *//*from  www.j a  v a  2  s .c  om*/
public static boolean saveThumbnail(Bitmap bitmap, String isbn) {
    // make sure we have access to the SD card
    if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
        try {
            // if the folder on the SD carld doesn't exist, create it
            if (!(new File(Environment.getExternalStorageDirectory(), path).exists())) {
                new File(Environment.getExternalStorageDirectory(), path).mkdirs();
                // creates the ".nomedia" file to hide content from "Gallery"
                new File(Environment.getExternalStorageDirectory(), path + ".nomedia").createNewFile();
            }

            // create the thumbnail
            File thumbnail = new File(Environment.getExternalStorageDirectory(), path + isbn + ".jpg");

            // if the file doesn't exist, create it and get the data
            if (!thumbnail.exists()) {
                thumbnail.createNewFile();
                FileOutputStream out = new FileOutputStream(thumbnail);

                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
            }

        } catch (IOException e) {
            Log.e(TAG, "IOException", e);
        }
    } else {
        return false;
    }
    return true;
}