Example usage for android.os Environment MEDIA_UNMOUNTED

List of usage examples for android.os Environment MEDIA_UNMOUNTED

Introduction

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

Prototype

String MEDIA_UNMOUNTED

To view the source code for android.os Environment MEDIA_UNMOUNTED.

Click Source Link

Document

Storage state if the media is present but not mounted.

Usage

From source file:com.tcl.lzhang1.mymusic.MusicUtil.java

/**
 * scan music in sdcard/*from  w w w. jav a2 s.c o  m*/
 * 
 * @return
 * @throws SDCardUnMoutedException
 */
public static List<SongModel> scanMusic(Context context) throws SDCardUnMoutedException {
    // onle scan sdcard path

    sContext = context;

    if (Environment.getExternalStorageState().equals(Environment.MEDIA_UNMOUNTED)) {
        throw new SDCardUnMoutedException("sorry sdcard was not mounted");
    }

    if (null != mSongs) {
        mSongs.clear();
    }
    File rootFile = Environment.getExternalStorageDirectory().getAbsoluteFile();

    scanFile(rootFile);

    if (null != mSongs && mScanListener != null) {
        mScanListener.onMusicScanedFinish();
    }

    return mSongs;
}

From source file:it.fabaris.wfp.application.Collect.java

/**
 * Creates required directories on the SDCard (or other external storage)
 * @throws RuntimeException if there is no SDCard or the directory exists as a non directory
 *//* w ww  .j  a va  2  s  . c  o  m*/
public static void createODKDirs() throws RuntimeException {
    String cardstatus = Environment.getExternalStorageState();

    if (cardstatus.equals(Environment.MEDIA_REMOVED) || cardstatus.equals(Environment.MEDIA_UNMOUNTABLE)
            || cardstatus.equals(Environment.MEDIA_UNMOUNTED)
            || cardstatus.equals(Environment.MEDIA_MOUNTED_READ_ONLY)
            || cardstatus.equals(Environment.MEDIA_SHARED)) {
        RuntimeException e = new RuntimeException(
                "ODK reports :: SDCard error: " + Environment.getExternalStorageState());
        throw e;
    }

    String[] dirs = { FABARISODK_ROOT, FORMS_PATH, INSTANCES_PATH, CACHE_PATH, METADATA_PATH };
    //        String[] dirs_Ext = {FABARISODK_ROOT_Ext, FORMS_PATH_Ext, INSTANCES_PATH_Ext, CACHE_PATH_Ext, METADATA_PATH_Ext};

    for (String dirName : dirs) {
        File dir = new File(dirName);

        if (!dir.exists()) {
            if (!dir.mkdirs()) {
                RuntimeException e = new RuntimeException("ODK reports :: Cannot create directory: " + dirName);
                throw e;
            }
        } else {
            if (!dir.isDirectory()) {
                RuntimeException e = new RuntimeException(
                        "ODK reports :: " + dirName + " exists, but is not a directory");
                throw e;
            }
        }
    }
}

From source file:com.connectsdk.device.DefaultConnectableDeviceStore.java

public DefaultConnectableDeviceStore(Context context) {
    String dirPath;/* w  w w . ja  v a  2 s  .co m*/
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        dirPath = Environment.getExternalStorageDirectory().getAbsolutePath();
    } else {
        dirPath = Environment.MEDIA_UNMOUNTED;
    }
    fileFullPath = dirPath + DIRPATH + FILENAME;

    try {
        fileFullPath = context.getPackageManager().getPackageInfo(context.getPackageName(),
                0).applicationInfo.dataDir + "/" + FILENAME;
    } catch (NameNotFoundException e) {
        e.printStackTrace();
    }

    load();
}

From source file:org.opendatakit.utilities.ODKFileUtils.java

public static void verifyExternalStorageAvailability() {
    String cardstatus = Environment.getExternalStorageState();
    if (cardstatus.equals(Environment.MEDIA_REMOVED) || cardstatus.equals(Environment.MEDIA_UNMOUNTABLE)
            || cardstatus.equals(Environment.MEDIA_UNMOUNTED)
            || cardstatus.equals(Environment.MEDIA_MOUNTED_READ_ONLY)
            || cardstatus.equals(Environment.MEDIA_SHARED)) {
        throw new RuntimeException("ODK reports :: SDCard error: " + Environment.getExternalStorageState());
    }// w ww . ja  va2s  .com
}

From source file:com.android.server.MountService.java

private void handleSystemReady() {
    // Snapshot current volume states since it's not safe to call into vold
    // while holding locks.
    final HashMap<String, String> snapshot;
    synchronized (mVolumesLock) {
        snapshot = new HashMap<String, String>(mVolumeStates);
    }//  www .  j  av  a  2s .  c o  m

    for (Map.Entry<String, String> entry : snapshot.entrySet()) {
        final String path = entry.getKey();
        final String state = entry.getValue();

        if (state.equals(Environment.MEDIA_UNMOUNTED)) {
            int rc = doMountVolume(path);
            if (rc != StorageResultCode.OperationSucceeded) {
                Slog.e(TAG, String.format("Boot-time mount failed (%d)", rc));
            }
        } else if (state.equals(Environment.MEDIA_SHARED)) {
            /*
             * Bootstrap UMS enabled state since vold indicates
             * the volume is shared (runtime restart while ums enabled)
             */
            notifyVolumeStateChange(null, path, VolumeState.NoMedia, VolumeState.Shared);
        }
    }

    // Push mounted state for all emulated storage
    synchronized (mVolumesLock) {
        for (StorageVolume volume : mVolumes) {
            if (volume.isEmulated()) {
                updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
            }
        }
    }

    /*
     * If UMS was connected on boot, send the connected event
     * now that we're up.
     */
    if (mSendUmsConnectedOnBoot) {
        sendUmsIntent(true);
        mSendUmsConnectedOnBoot = false;
    }

    /*
     * Start scheduling nominally-daily fstrim operations
     */
    MountServiceIdler.scheduleIdlePass(mContext);
}

From source file:com.android.server.MountService.java

private void updatePublicVolumeState(StorageVolume volume, String state) {
    final String path = volume.getPath();
    final String oldState;
    synchronized (mVolumesLock) {
        oldState = mVolumeStates.put(path, state);
        volume.setState(state);/* w  ww. j a  va 2 s  . c o m*/
    }

    if (state.equals(oldState)) {
        Slog.w(TAG, String.format("Duplicate state transition (%s -> %s) for %s", state, state, path));
        return;
    }

    Slog.d(TAG, "volume state changed for " + path + " (" + oldState + " -> " + state + ")");

    // Tell PackageManager about changes to primary volume state, but only
    // when not emulated.
    if (volume.isPrimary() && !volume.isEmulated()) {
        if (Environment.MEDIA_UNMOUNTED.equals(state)) {
            mPms.updateExternalMediaStatus(false, false);

            /*
             * Some OBBs might have been unmounted when this volume was
             * unmounted, so send a message to the handler to let it know to
             * remove those from the list of mounted OBBS.
             */
            mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_FLUSH_MOUNT_STATE, path));
        } else if (Environment.MEDIA_MOUNTED.equals(state)) {
            mPms.updateExternalMediaStatus(true, false);
        }
    }

    synchronized (mListeners) {
        for (int i = mListeners.size() - 1; i >= 0; i--) {
            MountServiceBinderListener bl = mListeners.get(i);
            try {
                bl.mListener.onStorageStateChanged(path, oldState, state);
            } catch (RemoteException rex) {
                Slog.e(TAG, "Listener dead");
                mListeners.remove(i);
            } catch (Exception ex) {
                Slog.e(TAG, "Listener failed", ex);
            }
        }
    }
}

From source file:com.android.server.MountService.java

/**
 * Callback from NativeDaemonConnector//from  w  w w  . j  a v a 2  s . com
 */
public void onDaemonConnected() {
    /*
     * Since we'll be calling back into the NativeDaemonConnector,
     * we need to do our work in a new thread.
     */
    new Thread("MountService#onDaemonConnected") {
        @Override
        public void run() {
            /**
             * Determine media state and UMS detection status
             */
            try {
                final String[] vols = NativeDaemonEvent.filterMessageList(
                        mConnector.executeForList("volume", "list", "broadcast"),
                        VoldResponseCode.VolumeListResult);
                for (String volstr : vols) {
                    String[] tok = volstr.split(" ");
                    // FMT: <label> <mountpoint> <state>
                    String path = tok[1];
                    String state = Environment.MEDIA_REMOVED;

                    final StorageVolume volume;
                    synchronized (mVolumesLock) {
                        volume = mVolumesByPath.get(path);
                    }

                    int st = Integer.parseInt(tok[2]);
                    if (st == VolumeState.NoMedia) {
                        state = Environment.MEDIA_REMOVED;
                    } else if (st == VolumeState.Idle) {
                        state = Environment.MEDIA_UNMOUNTED;
                    } else if (st == VolumeState.Mounted) {
                        state = Environment.MEDIA_MOUNTED;
                        Slog.i(TAG, "Media already mounted on daemon connection");
                    } else if (st == VolumeState.Shared) {
                        state = Environment.MEDIA_SHARED;
                        Slog.i(TAG, "Media shared on daemon connection");
                    } else {
                        throw new Exception(String.format("Unexpected state %d", st));
                    }

                    if (state != null) {
                        if (DEBUG_EVENTS)
                            Slog.i(TAG, "Updating valid state " + state);
                        updatePublicVolumeState(volume, state);
                    }
                }
            } catch (Exception e) {
                Slog.e(TAG, "Error processing initial volume state", e);
                final StorageVolume primary = getPrimaryPhysicalVolume();
                if (primary != null) {
                    updatePublicVolumeState(primary, Environment.MEDIA_REMOVED);
                }
            }

            /*
             * Now that we've done our initialization, release
             * the hounds!
             */
            mConnectedSignal.countDown();

            // On an encrypted device we can't see system properties yet, so pull
            // the system locale out of the mount service.
            if ("".equals(SystemProperties.get("vold.encrypt_progress"))) {
                copyLocaleFromMountService();
            }

            // Let package manager load internal ASECs.
            mPms.scanAvailableAsecs();

            // Notify people waiting for ASECs to be scanned that it's done.
            mAsecsScanned.countDown();
        }
    }.start();
}

From source file:com.android.server.MountService.java

/**
 * Callback from NativeDaemonConnector//  w  ww . j  a  v a  2 s . c om
 */
public boolean onEvent(int code, String raw, String[] cooked) {
    if (DEBUG_EVENTS) {
        StringBuilder builder = new StringBuilder();
        builder.append("onEvent::");
        builder.append(" raw= " + raw);
        if (cooked != null) {
            builder.append(" cooked = ");
            for (String str : cooked) {
                builder.append(" " + str);
            }
        }
        Slog.i(TAG, builder.toString());
    }
    if (code == VoldResponseCode.VolumeStateChange) {
        /*
         * One of the volumes we're managing has changed state.
         * Format: "NNN Volume <label> <path> state changed
         * from <old_#> (<old_str>) to <new_#> (<new_str>)"
         */
        notifyVolumeStateChange(cooked[2], cooked[3], Integer.parseInt(cooked[7]),
                Integer.parseInt(cooked[10]));
    } else if (code == VoldResponseCode.VolumeUuidChange) {
        // Format: nnn <label> <path> <uuid>
        final String path = cooked[2];
        final String uuid = (cooked.length > 3) ? cooked[3] : null;

        final StorageVolume vol = mVolumesByPath.get(path);
        if (vol != null) {
            vol.setUuid(uuid);
        }

    } else if (code == VoldResponseCode.VolumeUserLabelChange) {
        // Format: nnn <label> <path> <label>
        final String path = cooked[2];
        final String userLabel = (cooked.length > 3) ? cooked[3] : null;

        final StorageVolume vol = mVolumesByPath.get(path);
        if (vol != null) {
            vol.setUserLabel(userLabel);
        }

    } else if ((code == VoldResponseCode.VolumeDiskInserted) || (code == VoldResponseCode.VolumeDiskRemoved)
            || (code == VoldResponseCode.VolumeBadRemoval)) {
        // FMT: NNN Volume <label> <mountpoint> disk inserted (<major>:<minor>)
        // FMT: NNN Volume <label> <mountpoint> disk removed (<major>:<minor>)
        // FMT: NNN Volume <label> <mountpoint> bad removal (<major>:<minor>)
        String action = null;
        final String label = cooked[2];
        final String path = cooked[3];
        int major = -1;
        int minor = -1;

        try {
            String devComp = cooked[6].substring(1, cooked[6].length() - 1);
            String[] devTok = devComp.split(":");
            major = Integer.parseInt(devTok[0]);
            minor = Integer.parseInt(devTok[1]);
        } catch (Exception ex) {
            Slog.e(TAG, "Failed to parse major/minor", ex);
        }

        final StorageVolume volume;
        final String state;
        synchronized (mVolumesLock) {
            volume = mVolumesByPath.get(path);
            state = mVolumeStates.get(path);
        }

        if (code == VoldResponseCode.VolumeDiskInserted) {
            new Thread("MountService#VolumeDiskInserted") {
                @Override
                public void run() {
                    try {
                        int rc;
                        if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
                            Slog.w(TAG, String.format("Insertion mount failed (%d)", rc));
                        }
                    } catch (Exception ex) {
                        Slog.w(TAG, "Failed to mount media on insertion", ex);
                    }
                }
            }.start();
        } else if (code == VoldResponseCode.VolumeDiskRemoved) {
            /*
             * This event gets trumped if we're already in BAD_REMOVAL state
             */
            if (getVolumeState(path).equals(Environment.MEDIA_BAD_REMOVAL)) {
                return true;
            }
            /* Send the media unmounted event first */
            if (DEBUG_EVENTS)
                Slog.i(TAG, "Sending unmounted event first");
            updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
            sendStorageIntent(Intent.ACTION_MEDIA_UNMOUNTED, volume, UserHandle.ALL);

            if (DEBUG_EVENTS)
                Slog.i(TAG, "Sending media removed");
            updatePublicVolumeState(volume, Environment.MEDIA_REMOVED);
            action = Intent.ACTION_MEDIA_REMOVED;
        } else if (code == VoldResponseCode.VolumeBadRemoval) {
            if (DEBUG_EVENTS)
                Slog.i(TAG, "Sending unmounted event first");
            /* Send the media unmounted event first */
            updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
            sendStorageIntent(Intent.ACTION_MEDIA_UNMOUNTED, volume, UserHandle.ALL);

            if (DEBUG_EVENTS)
                Slog.i(TAG, "Sending media bad removal");
            updatePublicVolumeState(volume, Environment.MEDIA_BAD_REMOVAL);
            action = Intent.ACTION_MEDIA_BAD_REMOVAL;
        } else if (code == VoldResponseCode.FstrimCompleted) {
            EventLogTags.writeFstrimFinish(SystemClock.elapsedRealtime());
        } else {
            Slog.e(TAG, String.format("Unknown code {%d}", code));
        }

        if (action != null) {
            sendStorageIntent(action, volume, UserHandle.ALL);
        }
    } else {
        return false;
    }

    return true;
}

From source file:com.android.server.MountService.java

private void notifyVolumeStateChange(String label, String path, int oldState, int newState) {
    final StorageVolume volume;
    final String state;
    synchronized (mVolumesLock) {
        volume = mVolumesByPath.get(path);
        state = getVolumeState(path);/*  ww  w  .j a v  a  2s . c om*/
    }

    if (DEBUG_EVENTS)
        Slog.i(TAG, "notifyVolumeStateChange::" + state);

    String action = null;

    if (oldState == VolumeState.Shared && newState != oldState) {
        if (LOCAL_LOGD)
            Slog.d(TAG, "Sending ACTION_MEDIA_UNSHARED intent");
        sendStorageIntent(Intent.ACTION_MEDIA_UNSHARED, volume, UserHandle.ALL);
    }

    if (newState == VolumeState.Init) {
    } else if (newState == VolumeState.NoMedia) {
        // NoMedia is handled via Disk Remove events
    } else if (newState == VolumeState.Idle) {
        /*
         * Don't notify if we're in BAD_REMOVAL, NOFS, UNMOUNTABLE, or
         * if we're in the process of enabling UMS
         */
        if (!state.equals(Environment.MEDIA_BAD_REMOVAL) && !state.equals(Environment.MEDIA_NOFS)
                && !state.equals(Environment.MEDIA_UNMOUNTABLE) && !getUmsEnabling()) {
            if (DEBUG_EVENTS)
                Slog.i(TAG, "updating volume state for media bad removal nofs and unmountable");
            updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
            action = Intent.ACTION_MEDIA_UNMOUNTED;
        }
    } else if (newState == VolumeState.Pending) {
    } else if (newState == VolumeState.Checking) {
        if (DEBUG_EVENTS)
            Slog.i(TAG, "updating volume state checking");
        updatePublicVolumeState(volume, Environment.MEDIA_CHECKING);
        action = Intent.ACTION_MEDIA_CHECKING;
    } else if (newState == VolumeState.Mounted) {
        if (DEBUG_EVENTS)
            Slog.i(TAG, "updating volume state mounted");
        updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
        action = Intent.ACTION_MEDIA_MOUNTED;
    } else if (newState == VolumeState.Unmounting) {
        action = Intent.ACTION_MEDIA_EJECT;
    } else if (newState == VolumeState.Formatting) {
    } else if (newState == VolumeState.Shared) {
        if (DEBUG_EVENTS)
            Slog.i(TAG, "Updating volume state media mounted");
        /* Send the media unmounted event first */
        updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
        sendStorageIntent(Intent.ACTION_MEDIA_UNMOUNTED, volume, UserHandle.ALL);

        if (DEBUG_EVENTS)
            Slog.i(TAG, "Updating media shared");
        updatePublicVolumeState(volume, Environment.MEDIA_SHARED);
        action = Intent.ACTION_MEDIA_SHARED;
        if (LOCAL_LOGD)
            Slog.d(TAG, "Sending ACTION_MEDIA_SHARED intent");
    } else if (newState == VolumeState.SharedMnt) {
        Slog.e(TAG, "Live shared mounts not supported yet!");
        return;
    } else {
        Slog.e(TAG, "Unhandled VolumeState {" + newState + "}");
    }

    if (action != null) {
        sendStorageIntent(action, volume, UserHandle.ALL);
    }
}

From source file:com.android.server.MountService.java

private void readStorageListLocked() {
    mVolumes.clear();//from w  w w  . j ava  2 s .c o  m
    mVolumeStates.clear();

    Resources resources = mContext.getResources();

    int id = com.android.internal.R.xml.storage_list;
    XmlResourceParser parser = resources.getXml(id);
    AttributeSet attrs = Xml.asAttributeSet(parser);

    try {
        XmlUtils.beginDocument(parser, TAG_STORAGE_LIST);
        while (true) {
            XmlUtils.nextElement(parser);

            String element = parser.getName();
            if (element == null)
                break;

            if (TAG_STORAGE.equals(element)) {
                TypedArray a = resources.obtainAttributes(attrs, com.android.internal.R.styleable.Storage);

                String path = a.getString(com.android.internal.R.styleable.Storage_mountPoint);
                int descriptionId = a.getResourceId(com.android.internal.R.styleable.Storage_storageDescription,
                        -1);
                CharSequence description = a
                        .getText(com.android.internal.R.styleable.Storage_storageDescription);
                boolean primary = a.getBoolean(com.android.internal.R.styleable.Storage_primary, false);
                boolean removable = a.getBoolean(com.android.internal.R.styleable.Storage_removable, false);
                boolean emulated = a.getBoolean(com.android.internal.R.styleable.Storage_emulated, false);
                int mtpReserve = a.getInt(com.android.internal.R.styleable.Storage_mtpReserve, 0);
                boolean allowMassStorage = a
                        .getBoolean(com.android.internal.R.styleable.Storage_allowMassStorage, false);
                boolean allowMtp = a.getBoolean(com.android.internal.R.styleable.Storage_allowMtp, true);
                // resource parser does not support longs, so XML value is in megabytes
                long maxFileSize = a.getInt(com.android.internal.R.styleable.Storage_maxFileSize, 0) * 1024L
                        * 1024L;

                Slog.d(TAG,
                        "got storage path: " + path + " description: " + description + " primary: " + primary
                                + " removable: " + removable + " emulated: " + emulated + " mtpReserve: "
                                + mtpReserve + " allowMassStorage: " + allowMassStorage + " maxFileSize: "
                                + maxFileSize + " allowMtp: " + allowMtp);

                if (emulated) {
                    // For devices with emulated storage, we create separate
                    // volumes for each known user.
                    mEmulatedTemplate = new StorageVolume(null, descriptionId, true, false, true, mtpReserve,
                            false, maxFileSize, null, allowMtp);

                    final UserManagerService userManager = UserManagerService.getInstance();
                    for (UserInfo user : userManager.getUsers(false)) {
                        createEmulatedVolumeForUserLocked(user.getUserHandle());
                    }

                } else {
                    if (path == null || description == null) {
                        Slog.e(TAG, "Missing storage path or description in readStorageList");
                    } else {
                        final StorageVolume volume = new StorageVolume(new File(path), descriptionId, primary,
                                removable, emulated, mtpReserve, allowMassStorage, maxFileSize, null, allowMtp);
                        addVolumeLocked(volume);

                        // Until we hear otherwise, treat as unmounted
                        mVolumeStates.put(volume.getPath(), Environment.MEDIA_UNMOUNTED);
                        volume.setState(Environment.MEDIA_UNMOUNTED);
                    }
                }

                a.recycle();
            }
        }
    } catch (XmlPullParserException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        // Compute storage ID for each physical volume; emulated storage is
        // always 0 when defined.
        int index = isExternalStorageEmulated() ? 1 : 0;
        for (StorageVolume volume : mVolumes) {
            if (!volume.isEmulated()) {
                volume.setStorageId(index++);
            }
        }
        parser.close();
    }
}