Example usage for android.support.v4.os EnvironmentCompat getStorageState

List of usage examples for android.support.v4.os EnvironmentCompat getStorageState

Introduction

In this page you can find the example usage for android.support.v4.os EnvironmentCompat getStorageState.

Prototype

public static String getStorageState(File file) 

Source Link

Usage

From source file:org.y20k.transistor.helpers.StorageHelper.java

public File getCollectionDirectory() {
    String subDirectory = "Collection";
    File[] storage = (mActivity != null) ? mActivity.getExternalFilesDirs(subDirectory)
            : mContext.getExternalFilesDirs(subDirectory);
    for (File file : storage) {
        if (file != null) {
            String state = EnvironmentCompat.getStorageState(file);
            if (Environment.MEDIA_MOUNTED.equals(state)) {
                LogHelper.i(LOG_TAG, "External storage: " + file.toString());
                return file;
            }/*ww  w  . ja v a 2 s . c om*/
        }
    }
    return null;
}

From source file:org.dkf.jmule.util.SystemUtils.java

/**
 * Use this instead of EnvironmentCompat.
 * <p/>//from   w  w  w  .  j  ava  2  s.c om
 * returns true if the media is present
 * and mounted at its mount point with read/write access.
 *
 * @see android.os.Environment#MEDIA_MOUNTED
 */
public static boolean isSecondaryExternalStorageMounted(File path) {
    if (path == null) { // fast precondition
        return false;
    }

    boolean result = false;

    if (hasKitKatOrNewer()) {
        result = Environment.MEDIA_MOUNTED.equals(EnvironmentCompat.getStorageState(path));
    } else {
        try {
            String[] l = path.list();
            result = l != null && l.length > 0;
        } catch (Exception e) {
            LOG.error("Error detecting secondary external storage state {}", e);
        }
    }

    return result;
}

From source file:com.bt.download.android.util.SystemUtils.java

/**
 * Use this instead of EnvironmentCompat.
 * <p/>/*from ww  w .  j  a va  2 s.  c o m*/
 * returns true if the media is present
 * and mounted at its mount point with read/write access.
 *
 * @param path
 * @return
 * @see android.os.Environment#MEDIA_MOUNTED
 */
public static boolean isSecondaryExternalStorageMounted(File path) {
    if (path == null) { // fast precondition
        return false;
    }

    boolean result = false;

    if (hasKitKat()) {
        result = Environment.MEDIA_MOUNTED.equals(EnvironmentCompat.getStorageState(path));
    } else {
        try {
            String[] l = path.list();
            result = l != null && l.length > 0;
        } catch (Throwable e) {
            LOG.error("Error detecting secondary external storage state", e);
        }
    }

    return result;
}

From source file:com.xbm.android.matisse.internal.utils.MediaStoreCompat.java

private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
    String imageFileName = String.format("JPEG_%s.jpg", timeStamp);
    File storageDir;//from  w w  w . j a  v  a 2 s .  c  om
    if (mCaptureStrategy.isPublic) {
        storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    } else {
        storageDir = mContext.get().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    }

    // Avoid joining path components manually
    File tempFile = new File(storageDir, imageFileName);

    // Handle the situation that user's external storage is not ready
    if (!Environment.MEDIA_MOUNTED.equals(EnvironmentCompat.getStorageState(tempFile))) {
        return null;
    }

    return tempFile;
}

From source file:com.raspi.chatapp.util.storage.file.LocalStorageProvider.java

@Override
public Cursor queryRoots(final String[] projection) throws FileNotFoundException {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        if (getContext() == null || ContextCompat.checkSelfPermission(getContext(),
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            return null;
        }//from   ww  w  .j  a v a2 s  .c o  m
        // Create a cursor with either the requested fields, or the default projection if "projection" is null.
        final MatrixCursor result = new MatrixCursor(projection != null ? projection : DEFAULT_ROOT_PROJECTION);
        // Add Home directory
        File homeDir = Environment.getExternalStorageDirectory();
        if (TextUtils.equals(Environment.getExternalStorageState(), Environment.MEDIA_MOUNTED)) {
            final MatrixCursor.RowBuilder row = result.newRow();
            // These columns are required
            row.add(Root.COLUMN_ROOT_ID, homeDir.getAbsolutePath());
            row.add(Root.COLUMN_DOCUMENT_ID, homeDir.getAbsolutePath());
            row.add(Root.COLUMN_TITLE, getContext().getString(R.string.home));
            row.add(Root.COLUMN_FLAGS,
                    Root.FLAG_LOCAL_ONLY | Root.FLAG_SUPPORTS_CREATE | Root.FLAG_SUPPORTS_IS_CHILD);
            row.add(Root.COLUMN_ICON, R.mipmap.ic_launcher);
            // These columns are optional
            row.add(Root.COLUMN_SUMMARY, homeDir.getAbsolutePath());
            row.add(Root.COLUMN_AVAILABLE_BYTES, new StatFs(homeDir.getAbsolutePath()).getAvailableBytes());
            // Root.COLUMN_MIME_TYPE is another optional column and useful if you have multiple roots with different
            // types of mime types (roots that don't match the requested mime type are automatically hidden)
        }
        // Add SD card directory
        File sdCard = new File("/storage/extSdCard");
        String storageState = EnvironmentCompat.getStorageState(sdCard);
        if (TextUtils.equals(storageState, Environment.MEDIA_MOUNTED)
                || TextUtils.equals(storageState, Environment.MEDIA_MOUNTED_READ_ONLY)) {
            final MatrixCursor.RowBuilder row = result.newRow();
            // These columns are required
            row.add(Root.COLUMN_ROOT_ID, sdCard.getAbsolutePath());
            row.add(Root.COLUMN_DOCUMENT_ID, sdCard.getAbsolutePath());
            row.add(Root.COLUMN_TITLE, getContext().getString(R.string.sd_card));
            // Always assume SD Card is read-only
            row.add(Root.COLUMN_FLAGS, Root.FLAG_LOCAL_ONLY);
            row.add(Root.COLUMN_ICON, R.drawable.ic_sd_card);
            row.add(Root.COLUMN_SUMMARY, sdCard.getAbsolutePath());
            row.add(Root.COLUMN_AVAILABLE_BYTES, new StatFs(sdCard.getAbsolutePath()).getAvailableBytes());
        }
        return result;
    } else
        return null;
}

From source file:dev.dworks.apps.anexplorer.provider.ExternalStorageProvider.java

@TargetApi(Build.VERSION_CODES.KITKAT)
private void updateVolumesLocked() {
    mRoots.clear();/*from  w ww .ja v  a 2 s. c  o  m*/
    mIdToPath.clear();
    mIdToRoot.clear();

    int count = 0;
    StorageUtils storageUtils = new StorageUtils(getContext());
    for (StorageVolume volume : storageUtils.getStorageMounts()) {
        final File path = volume.getPathFile();
        String state = EnvironmentCompat.getStorageState(path);
        final boolean mounted = Environment.MEDIA_MOUNTED.equals(state)
                || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state);
        if (!mounted)
            continue;

        final String rootId;
        final String title;
        if (volume.isPrimary && volume.isEmulated) {
            rootId = ROOT_ID_PRIMARY_EMULATED;
            title = getContext().getString(R.string.root_internal_storage);
        } else if (volume.getUuid() != null) {
            rootId = ROOT_ID_SECONDARY + volume.getLabel();
            String label = volume.getLabel();
            title = !TextUtils.isEmpty(label) ? label
                    : getContext().getString(R.string.root_external_storage) + (count > 0 ? " " + count : "");
            count++;
        } else {
            Log.d(TAG, "Missing UUID for " + volume.getPath() + "; skipping");
            continue;
        }

        if (mIdToPath.containsKey(rootId)) {
            Log.w(TAG, "Duplicate UUID " + rootId + "; skipping");
            continue;
        }

        try {
            if (null == path.listFiles()) {
                continue;
            }
            mIdToPath.put(rootId, path);
            final RootInfo root = new RootInfo();

            root.rootId = rootId;
            root.flags = Root.FLAG_SUPPORTS_CREATE | Root.FLAG_SUPPORTS_EDIT | Root.FLAG_LOCAL_ONLY
                    | Root.FLAG_ADVANCED | Root.FLAG_SUPPORTS_SEARCH | Root.FLAG_SUPPORTS_IS_CHILD;
            root.title = title;
            root.docId = getDocIdForFile(path);
            root.path = path.getPath();
            mRoots.add(root);
            mIdToRoot.put(rootId, root);
        } catch (FileNotFoundException e) {
            throw new IllegalStateException(e);
        }
    }

    Log.d(TAG, "After updating volumes, found " + mRoots.size() + " active roots");

    getContext().getContentResolver().notifyChange(DocumentsContract.buildRootsUri(AUTHORITY), null, false);
}

From source file:cordova.plugins.Diagnostic_External_Storage.java

/**
 * Returns all available external SD-Cards in the system.
 *
 * @return paths to all available external SD-Cards in the system.
 *///  w w  w . j a  v a  2 s . c o  m
protected String[] getStorageDirectories() {

    List<String> results = new ArrayList<String>();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { //Method 1 for KitKat & above
        File[] externalDirs = this.cordova.getActivity().getApplicationContext().getExternalFilesDirs(null);

        for (File file : externalDirs) {
            if (file == null) {
                continue;
            }
            String applicationPath = file.getPath();
            String rootPath = applicationPath.split("/Android")[0];

            boolean addPath = false;

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                addPath = Environment.isExternalStorageRemovable(file);
            } else {
                addPath = Environment.MEDIA_MOUNTED.equals(EnvironmentCompat.getStorageState(file));
            }

            if (addPath) {
                results.add(rootPath);
                results.add(applicationPath);
            }
        }
    }

    if (results.isEmpty()) { //Method 2 for all versions
        // better variation of: http://stackoverflow.com/a/40123073/5002496
        String output = "";
        try {
            final Process process = new ProcessBuilder().command("mount | grep /dev/block/vold")
                    .redirectErrorStream(true).start();
            process.waitFor();
            final InputStream is = process.getInputStream();
            final byte[] buffer = new byte[1024];
            while (is.read(buffer) != -1) {
                output = output + new String(buffer);
            }
            is.close();
        } catch (final Exception e) {
            e.printStackTrace();
        }
        if (!output.trim().isEmpty()) {
            String devicePoints[] = output.split("\n");
            for (String voldPoint : devicePoints) {
                results.add(voldPoint.split(" ")[2]);
            }
        }
    }

    //Below few lines is to remove paths which may not be external memory card, like OTG (feel free to comment them out)
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        for (int i = 0; i < results.size(); i++) {
            if (!results.get(i).toLowerCase().matches(".*[0-9a-f]{4}[-][0-9a-f]{4}.*")) {
                diagnostic.logDebug(results.get(i) + " might not be extSDcard");
                results.remove(i--);
            }
        }
    } else {
        for (int i = 0; i < results.size(); i++) {
            if (!results.get(i).toLowerCase().contains("ext")
                    && !results.get(i).toLowerCase().contains("sdcard")) {
                diagnostic.logDebug(results.get(i) + " might not be extSDcard");
                results.remove(i--);
            }
        }
    }

    String[] storageDirectories = new String[results.size()];
    for (int i = 0; i < results.size(); ++i)
        storageDirectories[i] = results.get(i);

    return storageDirectories;
}

From source file:org.goodev.droidddle.utils.IOUtil.java

public static File getBestAvailableCacheRoot(Context context) {
    File[] roots = ContextCompat.getExternalCacheDirs(context);
    if (roots != null) {
        for (File root : roots) {
            if (root == null) {
                continue;
            }//from   ww  w  .j av a 2s  .c  om

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

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

From source file:org.goodev.droidddle.utils.IOUtil.java

public static File getBestAvailableFilesRoot(Context context) {
    File[] roots = ContextCompat.getExternalFilesDirs(context, null);
    if (roots != null) {
        for (File root : roots) {
            if (root == null) {
                continue;
            }//from ww  w . j  av a2 s  .c o  m

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

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

From source file:com.just.agentweb.AgentWebUtils.java

static String getDiskExternalCacheDir(Context context) {

    File mFile = context.getExternalCacheDir();
    if (Environment.MEDIA_MOUNTED.equals(EnvironmentCompat.getStorageState(mFile))) {
        return mFile.getAbsolutePath();
    }/*from  w  w w .  ja v  a2 s .c  o  m*/
    return null;
}