Example usage for android.os Environment MEDIA_MOUNTED

List of usage examples for android.os Environment MEDIA_MOUNTED

Introduction

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

Prototype

String MEDIA_MOUNTED

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

Click Source Link

Document

Storage state if the media is present and mounted at its mount point with read/write access.

Usage

From source file:com.phonegap.DirectoryManager.java

/**
 * Determine if SD card exists.//  w  w w .  j  av  a 2 s.  co  m
 * 
 * @return            T=exists, F=not found
 */
protected static boolean testSaveLocationExists() {
    String sDCardStatus = Environment.getExternalStorageState();
    boolean status;

    // If SD card is mounted
    if (sDCardStatus.equals(Environment.MEDIA_MOUNTED)) {
        status = true;
    }

    // If no SD card
    else {
        status = false;
    }
    return status;
}

From source file:moodle.android.moodle.helpers.FileManager.java

public File DownloadFromUrl(String fileURL, String fileName, String courseDirectoryAndType) { //this is the downloader method

    File file = null;//from ww w.j  a  v a  2s  .c  o m
    try {
        URL url = new URL(fileURL); //you can write here any link

        boolean mExternalStorageAvailable = false;
        boolean mExternalStorageWriteable = false;
        String state = Environment.getExternalStorageState();

        if (Environment.MEDIA_MOUNTED.equals(state)) {
            // We can read and write the media
            mExternalStorageAvailable = mExternalStorageWriteable = true;
        } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            // We can only read the media
            mExternalStorageAvailable = true;
            mExternalStorageWriteable = false;
        } else {
            // Something else is wrong. It may be one of many other states, but all we need
            //  to know is we can neither read nor write
            mExternalStorageAvailable = mExternalStorageWriteable = false;
        }

        if (mExternalStorageAvailable || mExternalStorageWriteable) {

            // create a File object for the parent directory 
            File fileDirectory = new File(PATH + "/Moodle/" + courseDirectoryAndType);
            // have the object build the directory structure, if needed. 
            fileDirectory.mkdirs();
            // create a File object for the output file 
            file = new File(fileDirectory, fileName);

            long startTime = System.currentTimeMillis();
            Log.d(TAG, "download begining");
            Log.d(TAG, "download url:" + url);
            Log.d(TAG, "downloaded file name:" + fileName);

            /* Open a connection to that URL. */
            URLConnection ucon = url.openConnection();

            /*
             * Define InputStreams to read from the URLConnection.
             */
            InputStream is = ucon.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);

            /*
             * Read bytes to the Buffer until there is nothing more to read(-1).
             */
            ByteArrayBuffer baf = new ByteArrayBuffer(50);
            int current = 0;
            while ((current = bis.read()) != -1) {
                baf.append((byte) current);
            }

            /* Convert the Bytes read to a String. */
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(baf.toByteArray());
            fos.close();

            Log.d(TAG, "download ready in" + ((System.currentTimeMillis() - startTime) / 1000) + " sec");
        }

    } catch (IOException e) {
        Log.d(TAG, "Error: " + e);
    }

    return file;
}

From source file:com.ethanco.simpleframe.utils.ACache.java

/**
 * //from   w  w  w. j av a 2  s  .  com
 *
 * @param ctx
 * @param cacheName
 * @return
 */
private static File getDefualtCacheDir(Context ctx, String cacheName) {
    File f;
    if (USE_EXTERNAL) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            f = new File(ctx.getExternalCacheDir(), cacheName);
        } else {
            f = new File(ctx.getCacheDir(), cacheName);
        }
    } else {
        f = new File(ctx.getCacheDir(), cacheName);
    }
    return f;
}

From source file:net.dahanne.android.regalandroid.utils.FileUtils.java

/**
 * download the requested file from the gallery, and save it to cache
 * //from w  w w. j a  v a  2  s .  c  o m
 * @param context
 * @param fileName
 * @param extension
 * @param imageUrl
 * @param isTemporary
 * @return
 * @throws GalleryConnectionException
 * @throws FileHandlingException
 */
public File getFileFromGallery(Context context, String fileName, String extension, String imageUrl,
        boolean isTemporary, int albumName) throws GalleryConnectionException, FileHandlingException {
    logger.debug(
            "gettingFileFromGallery, fileName : {} -- extension : {} -- imageUrl : {} -- isTemporary : {} -- albumName : {}",
            new Object[] { fileName, extension, imageUrl, isTemporary, albumName });
    File imageFileOnExternalDirectory = null;
    try {
        InputStream inputStreamFromUrl = null;
        String storageState = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(storageState)) {
            logger.debug("storage is mounted");
            File savePath = new File(Settings.getReGalAndroidCachePath(context) + "/" + albumName);
            // if the cache has never been used before
            if (!savePath.exists()) {
                // we make sure regalandroid path exists (ex : /regalandroid)
                File regalAndroidDirectory = new File(Settings.getReGalAndroidPath(context));
                regalAndroidDirectory.mkdir();
                // we then create regalandroid cache path (tmp)
                File regalAndroidCacheDirectory = new File(Settings.getReGalAndroidCachePath(context));
                regalAndroidCacheDirectory.mkdir();
                // and also that the specific album folder exists, bug #65
                File albumCacheDirectory = new File(
                        Settings.getReGalAndroidCachePath(context) + "/" + albumName);
                albumCacheDirectory.mkdir();

                // issue #30 : insert the .nomedia file so that the dir
                // won't be parsed by other photo apps
                File noMediaFile = new File(
                        Settings.getReGalAndroidCachePath(context) + "/" + albumName + NO_CACHE_PATH);
                if (!noMediaFile.createNewFile()) {
                    throw new FileHandlingException(context.getString(R.string.external_storage_problem));
                }
            }
            // if the file downloaded is not a cache file, but a file to
            // keep
            if (!isTemporary) {
                savePath = new File(Settings.getReGalAndroidPath(context));
                // if there is no file extension, we add the one that
                // corresponds to the picture (if we have it)
                if (fileName.lastIndexOf(".") == -1 && !StringUtils.isEmpty(extension)) {
                    fileName = fileName + "." + extension;
                }
            }
            logger.debug("savePath is : {}", savePath);
            //in case the filename has special characters
            imageFileOnExternalDirectory = new File(savePath, fileName);
            inputStreamFromUrl = RemoteGalleryConnectionFactory.getInstance().getInputStreamFromUrl(imageUrl);
        } else {
            throw new FileHandlingException(context.getString(R.string.external_storage_problem));
        }
        FileOutputStream fos;
        fos = new FileOutputStream(imageFileOnExternalDirectory);
        byte[] buf = new byte[1024];
        int len;
        while ((len = inputStreamFromUrl.read(buf)) > 0) {
            fos.write(buf, 0, len);
        }
        fos.close();
        inputStreamFromUrl.close();

    } catch (FileNotFoundException e) {
        throw new FileHandlingException(e.getMessage());
    } catch (IOException e) {
        throw new FileHandlingException(e.getMessage());
    }
    return imageFileOnExternalDirectory;
}

From source file:com.makotosan.vimeodroid.vimeo.Methods.java

public static boolean isExternalStorageWritable() {
    boolean mExternalStorageAvailable = false;
    boolean mExternalStorageWriteable = false;

    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        mExternalStorageAvailable = mExternalStorageWriteable = true;
    } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        mExternalStorageAvailable = true;
        mExternalStorageWriteable = false;
    } else {//from   w w  w  .  j ava2  s  . c om
        mExternalStorageAvailable = mExternalStorageWriteable = false;
    }

    return mExternalStorageAvailable && mExternalStorageWriteable;
}

From source file:de.fmaul.android.cmis.utils.StorageUtils.java

public static File getDownloadRoot(Application app) throws StorageException {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        StringBuilder builder = new StringBuilder();
        builder.append(((CmisApp) app).getPrefs().getDownloadFolder());
        builder.append("/");
        builder.append(ROOT_FOLDER_APP);
        return new File(builder.toString());
    } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        throw new StorageException("Storage in Read Only Mode");
    } else {//from   ww w.  j  a  v  a 2s. c om
        throw new StorageException("Storage is unavailable");
    }
}

From source file:com.bellman.bible.android.view.activity.StartupActivity.java

/**
 * Called when the activity is first created.
 *///from   www .jav  a  2  s.c  om
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //        setContentView(R.layout.startup_view);

    mIntent = getIntent();
    // do not show an actionBar/title on the splash screen
    getSupportActionBar().hide();

    //get the linear layout
    //        pHolder = (LinearLayout) findViewById(R.id.progress_holder);

    //        TextView versionTextView = (TextView) findViewById(R.id.versionText);
    //        String versionMsg = CurrentActivityHolder.getInstance().getApplication().getString(R.string.version_text, CommonUtils.getApplicationVersionName());
    //        versionTextView.setText(versionMsg);

    //See if any errors occurred during app initialisation, especially upgrade tasks
    // TODO: 8/15/2016 Remember changes made here
    int abortErrorMsgId = 0;//BibleApplication.getApplication(.getErrorDuringStartup();

    // check for SD card 
    // it would be great to check in the Application but how to show dialog from Application?
    if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
        abortErrorMsgId = R.string.no_sdcard_error;
    }

    // show fatal startup msg and close app
    if (abortErrorMsgId != 0) {
        Dialogs.getInstance().showErrorMsg(abortErrorMsgId, new Callback() {
            @Override
            public void okay() {
                // this causes the blue splashscreen activity to finish and since it is the top the app closes
                finish();
            }
        });
        // this aborts further initialisation but leaves blue splashscreen activity
        return;
    }

    // allow call back and continuation in the ui thread after JSword has been initialised
    final Handler uiHandler = new Handler();
    final Runnable uiThreadRunnable = new Runnable() {

        @Override
        public void run() {
            postBasicInitialisationControl();
        }
    };

    // initialise JSword in another thread (takes a long time) then call main ui thread Handler to continue
    // this allows the splash screen to be displayed and an hourglass to run
    new Thread() {
        public void run() {
            try {
                // allow the splash screen to be displayed immediately
                CommonUtils.pauseMillis(1);

                // force Sword to initialise itself
                Initialisation.getInstance().initialiseNow();
            } finally {
                // switch back to ui thread to continue
                uiHandler.post(uiThreadRunnable);
            }
        }
    }.start();
}

From source file:cat.joronya.utils.image.ImageDownloader.java

public ImageDownloader(Context context, String cachedir, String subdir, int requiredSize) {
    this.context = context;
    this.requiredSize = requiredSize;

    File firstCacheDir = null;/*from w w w .  j a  v  a  2 s  . c o  m*/
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        if (cachedir == null && "".equals(cachedir))
            firstCacheDir = new File(Environment.getExternalStorageDirectory(), CACHE_DIR);
        else
            firstCacheDir = new File(Environment.getExternalStorageDirectory(), cachedir);
    } else {
        firstCacheDir = context.getCacheDir();
    }

    // el sub cache dir
    cacheDir = new File(firstCacheDir, subdir);
    if (!cacheDir.exists())
        cacheDir.mkdirs();

    // preparem fitxer ".nomedia", pq el MediaScanner no trobi els fitxers
    File nomediaFile = new File(cacheDir, ".nomedia");
    if (!nomediaFile.exists())
        try {
            nomediaFile.createNewFile();
        } catch (IOException e) {
        }
}

From source file:com.github.piasy.common.android.utils.roms.RomUtil.java

/**
 * Checks if there is enough Space on SDCard
 *
 * @param updateSize Size to Check//from  w  w  w  . j  a v  a2s.  c  o  m
 * @return {@code true} if the Update will fit on SDCard, {@code false} if not enough space on
 * SDCard. Will also return false, if the SDCard is not mounted as read/write
 */
@SuppressWarnings("PMD.DataflowAnomalyAnalysis")
public boolean enoughSpaceOnSdCard(final long updateSize) {
    boolean ret = false;
    final String status = Environment.getExternalStorageState();
    if (status.equals(Environment.MEDIA_MOUNTED)) {
        final File path = Environment.getExternalStorageDirectory();
        final StatFs stat = new StatFs(path.getPath());
        final long blockSize = Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2
                ? stat.getBlockSizeLong()
                : stat.getBlockSize();
        final long availableBlocks = Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2
                ? stat.getAvailableBlocksLong()
                : stat.getAvailableBlocks();

        ret = updateSize < availableBlocks * blockSize;
    }

    return ret;
}

From source file:com.blork.anpod.util.BitmapUtils.java

public static BitmapResult fetchImage(Context context, Picture picture, int desiredWidth, int desiredHeight) {

    // First compute the cache key and cache file path for this URL
    File cacheFile = null;/* www. jav  a2s .  co m*/
    if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
        Log.d("APOD", "creating cache file");
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);

        if (prefs.getBoolean("archive", false)) {
            cacheFile = new File(Environment.getExternalStorageDirectory() + File.separator + "APOD"
                    + File.separator + toSlug(picture.title) + ".jpg");
        } else {
            cacheFile = new File(Environment.getExternalStorageDirectory() + File.separator + "Android"
                    + File.separator + "data" + File.separator + "com.blork.anpod" + File.separator + "cache"
                    + File.separator + toSlug(picture.title) + ".jpg");
        }
    } else {
        Log.d("APOD", "SD card not mounted");
        Log.d("APOD", "creating cache file");
        cacheFile = new File(context.getCacheDir() + File.separator + toSlug(picture.title) + ".jpg");
    }

    if (cacheFile != null && cacheFile.exists()) {
        Log.d("APOD", "Cache file exists, using it.");
        try {
            Bitmap bitmap = decodeStream(new FileInputStream(cacheFile), desiredWidth, desiredHeight);
            return new BitmapResult(bitmap, Uri.fromFile(cacheFile));
        } catch (FileNotFoundException e) {
        }
    }

    try {
        Log.d("APOD", "Not cached, fetching");
        BitmapUtils.manageCache(toSlug(picture.title), context);
        // TODO: check for HTTP caching headers
        final HttpClient httpClient = SyncUtils.getHttpClient(context.getApplicationContext());
        final HttpResponse resp = httpClient.execute(new HttpGet(picture.getFullSizeImageUrl()));
        final HttpEntity entity = resp.getEntity();

        final int statusCode = resp.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK || entity == null) {
            return null;
        }

        final byte[] respBytes = EntityUtils.toByteArray(entity);

        Log.d("APOD", "Writing cache file " + cacheFile.getName());
        try {
            cacheFile.getParentFile().mkdirs();
            cacheFile.createNewFile();
            FileOutputStream fos = new FileOutputStream(cacheFile);
            fos.write(respBytes);
            fos.close();
        } catch (FileNotFoundException e) {
            Log.d("APOD", "Error writing to bitmap cache: " + cacheFile.toString(), e);
        } catch (IOException e) {
            Log.d("APOD", "Error writing to bitmap cache: " + cacheFile.toString(), e);
        }

        // Decode the bytes and return the bitmap.
        Log.d("APOD", "Reiszing bitmap image");

        Bitmap bitmap = decodeStream(new ByteArrayInputStream(respBytes), desiredWidth, desiredHeight);
        Log.d("APOD", "Returning bitmap image");
        return new BitmapResult(bitmap, Uri.fromFile(cacheFile));
    } catch (Exception e) {
        Log.d("APOD", "Problem while loading image: " + e.toString(), e);
    }

    return null;
}