Example usage for android.os Environment MEDIA_SHARED

List of usage examples for android.os Environment MEDIA_SHARED

Introduction

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

Prototype

String MEDIA_SHARED

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

Click Source Link

Document

Storage state if the media is present not mounted, and shared via USB mass storage.

Usage

From source file:com.android.stockbrowser.DownloadHandler.java

private static void onDownloadNoStreamImpl(Activity activity, String url, String userAgent,
        String contentDisposition, String mimetype, String referer, boolean privateBrowsing) {

    String filename = URLUtil.guessFileName(url, contentDisposition, mimetype);

    // Check to see if we have an SDCard
    String status = Environment.getExternalStorageState();
    if (!status.equals(Environment.MEDIA_MOUNTED)) {
        int title;
        String msg;/*from w w  w  .  j av  a  2  s.c o  m*/

        // Check to see if the SDCard is busy, same as the music app
        if (status.equals(Environment.MEDIA_SHARED)) {
            msg = activity.getString(R.string.download_sdcard_busy_dlg_msg);
            title = R.string.download_sdcard_busy_dlg_title;
        } else {
            msg = activity.getString(R.string.download_no_sdcard_dlg_msg, filename);
            title = R.string.download_no_sdcard_dlg_title;
        }

        new AlertDialog.Builder(activity).setTitle(title).setIconAttribute(android.R.attr.alertDialogIcon)
                .setMessage(msg).setPositiveButton(R.string.ok, null).show();
        return;
    }

    // java.net.URI is a lot stricter than KURL so we have to encode some
    // extra characters. Fix for b 2538060 and b 1634719
    WebAddress webAddress;
    try {
        webAddress = new WebAddress(url);
        webAddress.setPath(encodePath(webAddress.getPath()));
    } catch (Exception e) {
        // This only happens for very bad urls, we want to chatch the
        // exception here
        Log.e(LOGTAG, "Exception trying to parse url:" + url);
        return;
    }

    String addressString = webAddress.toString();
    Uri uri = Uri.parse(addressString);
    final DownloadManager.Request request;
    try {
        request = new DownloadManager.Request(uri);
    } catch (IllegalArgumentException e) {
        Toast.makeText(activity, R.string.cannot_download, Toast.LENGTH_SHORT).show();
        return;
    }
    request.setMimeType(mimetype);
    // set downloaded file destination to /sdcard/Download.
    // or, should it be set to one of several Environment.DIRECTORY* dirs depending on mimetype?
    try {
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
    } catch (IllegalStateException ex) {
        // This only happens when directory Downloads can't be created or it isn't a directory
        // this is most commonly due to temporary problems with sdcard so show appropriate string
        Log.w(LOGTAG, "Exception trying to create Download dir:", ex);
        Toast.makeText(activity, R.string.download_sdcard_busy_dlg_title, Toast.LENGTH_SHORT).show();
        return;
    }
    // let this downloaded file be scanned by MediaScanner - so that it can
    // show up in Gallery app, for example.
    request.allowScanningByMediaScanner();
    request.setDescription(webAddress.getHost());
    // XXX: Have to use the old url since the cookies were stored using the
    // old percent-encoded url.
    String cookies = "";//CookieManager.getInstance().getCookie(url, privateBrowsing);
    request.addRequestHeader("cookie", cookies);
    request.addRequestHeader("User-Agent", userAgent);
    if (!TextUtils.isEmpty(referer)) {
        request.addRequestHeader("Referer", referer);
    }
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    if (mimetype == null) {
        if (TextUtils.isEmpty(addressString)) {
            return;
        }
        // We must have long pressed on a link or image to download it. We
        // are not sure of the mimetype in this case, so do a head request
        new FetchUrlMimeType(activity, request, addressString, cookies, userAgent).start();
    } else {
        final DownloadManager manager = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE);
        new Thread("StockBrowser download") {
            public void run() {
                manager.enqueue(request);
            }
        }.start();
    }
    Toast.makeText(activity, R.string.download_pending, Toast.LENGTH_SHORT).show();
}

From source file:com.android.browser.DownloadHandler.java

private static void onDownloadNoStreamImpl(Activity activity, String url, String userAgent,
        String contentDisposition, String mimetype, String referer, boolean privateBrowsing) {

    String filename = URLUtil.guessFileName(url, contentDisposition, mimetype);

    // Check to see if we have an SDCard
    String status = Environment.getExternalStorageState();
    if (!status.equals(Environment.MEDIA_MOUNTED)) {
        int title;
        String msg;//from  ww  w . ja  v  a  2 s .c om

        // Check to see if the SDCard is busy, same as the music app
        if (status.equals(Environment.MEDIA_SHARED)) {
            msg = activity.getString(R.string.download_sdcard_busy_dlg_msg);
            title = R.string.download_sdcard_busy_dlg_title;
        } else {
            msg = activity.getString(R.string.download_no_sdcard_dlg_msg, filename);
            title = R.string.download_no_sdcard_dlg_title;
        }

        new AlertDialog.Builder(activity).setTitle(title).setIconAttribute(android.R.attr.alertDialogIcon)
                .setMessage(msg).setPositiveButton(R.string.ok, null).show();
        return;
    }

    // java.net.URI is a lot stricter than KURL so we have to encode some
    // extra characters. Fix for b 2538060 and b 1634719
    WebAddress webAddress;
    try {
        webAddress = new WebAddress(url);
        webAddress.setPath(encodePath(webAddress.getPath()));
    } catch (Exception e) {
        // This only happens for very bad urls, we want to chatch the
        // exception here
        Log.e(LOGTAG, "Exception trying to parse url:" + url);
        return;
    }

    String addressString = webAddress.toString();
    Uri uri = Uri.parse(addressString);
    final DownloadManager.Request request;
    try {
        request = new DownloadManager.Request(uri);
    } catch (IllegalArgumentException e) {
        Toast.makeText(activity, R.string.cannot_download, Toast.LENGTH_SHORT).show();
        return;
    }
    request.setMimeType(mimetype);
    // set downloaded file destination to /sdcard/Download.
    // or, should it be set to one of several Environment.DIRECTORY* dirs depending on mimetype?
    try {
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
    } catch (IllegalStateException ex) {
        // This only happens when directory Downloads can't be created or it isn't a directory
        // this is most commonly due to temporary problems with sdcard so show appropriate string
        Log.w(LOGTAG, "Exception trying to create Download dir:", ex);
        Toast.makeText(activity, R.string.download_sdcard_busy_dlg_title, Toast.LENGTH_SHORT).show();
        return;
    }
    // let this downloaded file be scanned by MediaScanner - so that it can
    // show up in Gallery app, for example.
    request.allowScanningByMediaScanner();
    request.setDescription(webAddress.getHost());
    // XXX: Have to use the old url since the cookies were stored using the
    // old percent-encoded url.
    String cookies = CookieManager.getInstance().getCookie(url, privateBrowsing);
    request.addRequestHeader("cookie", cookies);
    request.addRequestHeader("User-Agent", userAgent);
    if (!TextUtils.isEmpty(referer)) {
        request.addRequestHeader("Referer", referer);
    }
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    if (mimetype == null) {
        if (TextUtils.isEmpty(addressString)) {
            return;
        }
        // We must have long pressed on a link or image to download it. We
        // are not sure of the mimetype in this case, so do a head request
        new FetchUrlMimeType(activity, request, addressString, cookies, userAgent).start();
    } else {
        final DownloadManager manager = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE);
        new Thread("Browser download") {
            public void run() {
                manager.enqueue(request);
            }
        }.start();
    }
    Toast.makeText(activity, R.string.download_pending, Toast.LENGTH_SHORT).show();
}

From source file:com.sabaibrowser.DownloadHandler.java

private static void onDownloadNoStreamImpl(Activity activity, String url, String userAgent,
        String contentDisposition, String mimetype, String referer, boolean privateBrowsing) {

    String filename = URLUtil.guessFileName(url, contentDisposition, mimetype);

    // Check to see if we have an SDCard
    String status = Environment.getExternalStorageState();
    if (!status.equals(Environment.MEDIA_MOUNTED)) {
        int title;
        String msg;//  w  ww.  j a  v a  2 s. c o  m

        // Check to see if the SDCard is busy, same as the music app
        if (status.equals(Environment.MEDIA_SHARED)) {
            msg = activity.getString(R.string.download_sdcard_busy_dlg_msg);
            title = R.string.download_sdcard_busy_dlg_title;
        } else {
            msg = activity.getString(R.string.download_no_sdcard_dlg_msg, filename);
            title = R.string.download_no_sdcard_dlg_title;
        }

        new AlertDialog.Builder(activity).setTitle(title).setIconAttribute(android.R.attr.alertDialogIcon)
                .setMessage(msg).setPositiveButton(R.string.ok, null).show();
        return;
    }

    // java.net.URI is a lot stricter than KURL so we have to encode some
    // extra characters. Fix for b 2538060 and b 1634719
    WebAddress webAddress;
    try {
        webAddress = new WebAddress(url);
        webAddress.setPath(encodePath(webAddress.getPath()));
    } catch (Exception e) {
        // This only happens for very bad urls, we want to chatch the
        // exception here
        Log.e(LOGTAG, "Exception trying to parse url:" + url);
        return;
    }

    String addressString = webAddress.toString();
    Uri uri = Uri.parse(addressString);
    final DownloadManager.Request request;
    try {
        request = new DownloadManager.Request(uri);
    } catch (IllegalArgumentException e) {
        Toast.makeText(activity, R.string.cannot_download, Toast.LENGTH_SHORT).show();
        return;
    }
    request.setMimeType(mimetype);
    // set downloaded file destination to /sdcard/Download.
    // or, should it be set to one of several Environment.DIRECTORY* dirs depending on mimetype?
    try {
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
    } catch (IllegalStateException ex) {
        // This only happens when directory Downloads can't be created or it isn't a directory
        // this is most commonly due to temporary problems with sdcard so show appropriate string
        Log.w(LOGTAG, "Exception trying to create Download dir:", ex);
        Toast.makeText(activity, R.string.download_sdcard_busy_dlg_title, Toast.LENGTH_SHORT).show();
        return;
    }
    // let this downloaded file be scanned by MediaScanner - so that it can
    // show up in Gallery app, for example.
    request.allowScanningByMediaScanner();
    request.setDescription(webAddress.getHost());
    // XXX: Have to use the old url since the cookies were stored using the
    // old percent-encoded url.
    String cookies = privateBrowsing ? "" : CookieManager.getInstance().getCookie(url);
    request.addRequestHeader("cookie", cookies);
    request.addRequestHeader("User-Agent", userAgent);
    if (!TextUtils.isEmpty(referer)) {
        request.addRequestHeader("Referer", referer);
    }
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    if (mimetype == null) {
        if (TextUtils.isEmpty(addressString)) {
            return;
        }
        // We must have long pressed on a link or image to download it. We
        // are not sure of the mimetype in this case, so do a head request
        new FetchUrlMimeType(activity, request, addressString, cookies, userAgent).start();
    } else {
        final DownloadManager manager = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE);
        new Thread("Browser download") {
            public void run() {
                manager.enqueue(request);
            }
        }.start();
    }
    Toast.makeText(activity, R.string.download_pending, Toast.LENGTH_SHORT).show();
}

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());
    }//from w  w  w .  ja  v a 2 s. co  m
}

From source file:org.geek.utils.ApplicationUtils.java

/**
 * Check if the SD card is available. Display an alert if not.
 * @param context The current context.//w  w  w .j a v  a  2  s  . c  o m
 * @param showMessage If true, will display a message for the user.
 * @return True if the SD card is available, false otherwise.
 */
public static boolean checkCardState(Context context, boolean showMessage) {
    // Check to see if we have an SDCard
    String status = Environment.getExternalStorageState();
    if (!status.equals(Environment.MEDIA_MOUNTED)) {

        int messageId;

        // Check to see if the SDCard is busy, same as the music app
        if (status.equals(Environment.MEDIA_SHARED)) {
            messageId = R.string.Commons_SDCardErrorSDUnavailable;
        } else {
            messageId = R.string.Commons_SDCardErrorNoSDMsg;
        }

        if (showMessage) {
            ApplicationUtils.showErrorDialog(context, R.string.Commons_SDCardErrorTitle, messageId);
        }

        return false;
    }

    return true;
}

From source file:com.coincollection.MainActivity.java

/**
 * Kicks off the import process by reading in the import files into our internal representation.
 * Once this is complete, it kicks off an AsyncTask to actually store the data in the database.
 *//*from   w  w w.j av  a  2 s.c  o m*/
private void handleImportCollectionsPart1() {

    // Check for READ_EXTERNAL_STORAGE permissions (must request starting in API Level 23)
    // hasPermissions() will kick off the permissions request and the handler will re-call
    // this method after prompting the user.
    if (!hasPermissions(Manifest.permission.READ_EXTERNAL_STORAGE, IMPORT_PERMISSIONS_REQUEST)) {
        return;
    }

    // See whether we can read from the external storage
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        // Should be able to read from it without issue
    } else if (Environment.MEDIA_SHARED.equals(state)) {
        // Shared with PC so can't write to it
        showCancelableAlert(mRes.getString(R.string.cannot_rd_ext_media_shared));
        return;
    } else {
        // Doesn't exist, so notify user
        showCancelableAlert(mRes.getString(R.string.cannot_rd_ext_media_state, state));
        return;
    }

    //http://stackoverflow.com/questions/3551821/android-write-to-sd-card-folder
    File sdCard = Environment.getExternalStorageDirectory();
    String path = sdCard.getAbsolutePath() + EXPORT_FOLDER_NAME;
    File dir = new File(path);

    if (!dir.isDirectory()) {
        // The directory doesn't exist, notify the user
        showCancelableAlert(mRes.getString(R.string.cannot_find_export_dir, path));
        return;
    }

    boolean errorOccurred = false;

    // Read the database version
    File inputFile = new File(dir, "database_version.txt");
    CSVReader in = openFileForReading(inputFile);
    if (in == null)
        return;

    try {
        String[] values = in.readNext();
        if (values == null || values.length != 1) {
            throw new Exception();
        }
        mDatabaseVersion = Integer.parseInt(values[0]);
    } catch (Exception e) {
        showCancelableAlert(mRes.getString(R.string.error_reading_file, inputFile.getAbsolutePath()));
        return;
    }

    if (-1 == mDatabaseVersion) {
        showCancelableAlert(mRes.getString(R.string.error_db_version));
        return;
    }

    if (!closeInputFile(in, inputFile)) {
        return;
    }

    // Read the collection_info table
    inputFile = new File(dir, "list-of-collections.csv");
    in = openFileForReading(inputFile);
    if (in == null)
        return;

    ArrayList<CollectionListInfo> collectionInfo = new ArrayList<>();

    try {
        String[] items;

        // TODO Raise an error if in.readNext returns null
        while (null != (items = in.readNext())) {

            // Perform some sanity checks here
            int numberOfColumns = 5;

            if (items.length != numberOfColumns) {
                errorOccurred = true;
                showCancelableAlert(mRes.getString(R.string.error_invalid_backup_file, 1));
                break;
            }

            String name = items[0];
            String type = items[1];
            int totalCollected = Integer.valueOf(items[2]);
            int total = Integer.valueOf(items[3]);
            int displayType = Integer.valueOf(items[4]);

            // Strip out all bad characters.  They shouldn't be there anyway ;)
            name = name.replace('[', ' ');
            name = name.replace(']', ' ');

            // Must be a valid coin type
            int i;
            for (i = 0; i < MainApplication.COLLECTION_TYPES.length; i++) {

                if (MainApplication.COLLECTION_TYPES[i].getCoinType().equals(type)) {
                    break;
                } else if (MainApplication.COLLECTION_TYPES.length == i + 1) {
                    errorOccurred = true;
                    showCancelableAlert(mRes.getString(R.string.error_invalid_backup_file, 2));
                    break;
                }
            }

            int coinTypeIndex = i;

            if (errorOccurred) {
                break;
            }

            // Must have a positive number collected and a positive max
            if (totalCollected < 0 || total < 0) {
                errorOccurred = true;
                showCancelableAlert(mRes.getString(R.string.error_invalid_backup_file, 3));
                break;
            }

            // Must not have a name that is the same as a previous one
            for (i = 0; i < collectionInfo.size(); i++) {

                CollectionListInfo previousCollectionListInfo = collectionInfo.get(i);
                if (name.equals(previousCollectionListInfo.getName())) {
                    errorOccurred = true;
                    showCancelableAlert(mRes.getString(R.string.error_invalid_backup_file, 4));
                    break;
                }
            }

            if (displayType != CollectionPage.SIMPLE_DISPLAY
                    && displayType != CollectionPage.ADVANCED_DISPLAY) {
                errorOccurred = true;
                showCancelableAlert(mRes.getString(R.string.error_invalid_backup_file, 5));
                break;
            }

            if (errorOccurred) {
                break;
            }

            // Everything checks out, so create a new CollectionListInfo
            // for this
            CollectionListInfo info = new CollectionListInfo(name, total, totalCollected, coinTypeIndex,
                    displayType);

            // Good to go, add it to the list
            collectionInfo.add(info);
        }
    } catch (Exception e) {
        errorOccurred = true;
        showCancelableAlert(mRes.getString(R.string.error_unknown_read, inputFile.getAbsolutePath()));
    }

    // Close the input file.  If we've already shown an error then no
    // need to show another one if the close fails
    if (!closeInputFile(in, inputFile, errorOccurred)) {
        return;
    }

    if (errorOccurred) {
        // Don't continue on
        return;
    }

    // The ArrayList will be indexed by collection, the outer String[] will be indexed
    // by line number, and the inner String[] will be each cell in the row
    ArrayList<String[][]> collectionContents = new ArrayList<>();

    // We loaded in the collection "metadata" table, so now load in each collection
    for (int i = 0; i < collectionInfo.size(); i++) {

        CollectionListInfo collectionData = collectionInfo.get(i);

        // If any '/''s exist in the collection name, change them to "_SL_" to match
        // the export logic (used to prevent slashes from being confused as path
        // delimiters when opening the file.)
        String collectionFileName = collectionData.getName().replaceAll("/", "_SL_");

        inputFile = new File(dir, collectionFileName + ".csv");

        if (!inputFile.isFile()) {
            showCancelableAlert(mRes.getString(R.string.cannot_find_input_file, inputFile.getAbsolutePath()));
            return;
        }

        in = openFileForReading(inputFile);
        if (in == null)
            return;

        ArrayList<String[]> collectionContent = new ArrayList<>();

        try {
            String[] items;
            while (null != (items = in.readNext())) {

                // Perform some sanity checks and clean-up here
                int numberOfColumns = 6;

                if (items.length < numberOfColumns) {
                    errorOccurred = true;
                    showCancelableAlert(mRes.getString(R.string.error_invalid_backup_file, 11) + " "
                            + String.valueOf(items.length));
                    break;
                }

                // TODO Maybe add more checks
                collectionContent.add(items);
            }

        } catch (Exception e) {
            errorOccurred = true;
            showCancelableAlert(mRes.getString(R.string.error_unknown_read, inputFile.getAbsolutePath()));
        }

        if (errorOccurred) {
            // Don't continue on
            closeInputFile(in, inputFile, true);
            return;
        }

        // Verify that we read in the correct number of records
        if (collectionContent.size() != collectionData.getMax()) {
            errorOccurred = true;
            showCancelableAlert(mRes.getString(R.string.error_invalid_backup_file, 12));
        }

        // TODO Can this happen? ClassCastException Object[] cannot be cast to String[][]
        collectionContents.add(collectionContent.toArray(new String[0][]));

        if (!closeInputFile(in, inputFile)) {
            return;
        }

        if (errorOccurred) {
            // Don't continue on
            return;
        }
    }

    // Cool, at this point we've read in the data successfully and we've passed all of
    // the sanity checks.  We should put this data aside, show the user a message to
    // have them confirm that they want to do this... Although if they don't have any
    // collections we can optimize this step out
    mImportedCollectionListInfos = collectionInfo;
    mCollectionContents = collectionContents;

    if (0 == mNumberOfCollections) {
        // Finish the import by kicking off an AsyncTask to do the heavy lifting          
        mTask = new InitTask();

        mTask.doImport = true;
        mTask.activity = this;

        mTask.execute();

    } else {
        showImportConfirmation();
    }
}

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);
    }//from   w w  w  .  j  a v  a2s  .  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

/**
 * Callback from NativeDaemonConnector/*from   w w  w .  j  a va2 s .  c  o m*/
 */
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.coincollection.MainActivity.java

/**
 * Begins the collection export process by doing some preliminary external media checks and
 * prompts the user if an export will overwrite previous backup files.
 *///  w ww .ja v a2  s  .  co  m
private void handleExportCollectionsPart1() {
    // TODO Move this function to be more resistant to ANR, if reports show that it is a
    // problem

    // Check for WRITE_EXTERNAL_STORAGE permissions (must request starting in API Level 23)
    // hasPermissions() will kick off the permissions request and the handler will re-call
    // this method after prompting the user.
    if (!hasPermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE, EXPORT_PERMISSIONS_REQUEST)) {
        return;
    }

    // See whether we can write to the external storage
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        // Should be able to write to it without issue
    } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        // Can't write to it, so notify user
        showCancelableAlert(mRes.getString(R.string.cannot_wr_ext_media_ro));
        return;
    } else if (Environment.MEDIA_SHARED.equals(state)) {
        // Shared with PC so can't write to it
        showCancelableAlert(mRes.getString(R.string.cannot_wr_ext_media_shared));
        return;
    } else {
        // Doesn't exist, so notify user
        showCancelableAlert(mRes.getString(R.string.cannot_wr_ext_media_state, state));
        return;
    }

    //http://stackoverflow.com/questions/3551821/android-write-to-sd-card-folder
    File sdCard = Environment.getExternalStorageDirectory();
    String path = sdCard.getAbsolutePath() + EXPORT_FOLDER_NAME;
    File dir = new File(path);

    if (dir.isDirectory() || dir.exists()) {
        // Let the user decide whether they want to delete this
        showExportConfirmation();
    } else {
        // Proceed with exporting directly
        handleExportCollectionsPart2();
    }
}

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);/*from   w  w  w .j  av 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);
    }
}