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: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  . ja  v  a2s.  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.bellman.bible.android.view.activity.StartupActivity.java

/**
 * Called when the activity is first created.
 *///www .j  av  a2  s .c  o m
@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:com.radicaldynamic.groupinform.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 w  w.jav a  2 s  . c  om*/
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 = { ODK_ROOT, FORMS_PATH, INSTANCES_PATH, CACHE_PATH, METADATA_PATH };

    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.github.piasy.common.android.utils.roms.RomUtil.java

/**
 * Checks if there is enough Space on SDCard
 *
 * @param updateSize Size to Check/*w w w. j  a  v a2 s . c om*/
 * @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;// ww w  .ja v  a 2 s  . com
    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;
}

From source file:com.lxh.util.image.OtherUtils.java

/**
 * ??//from w w  w  .j  a v  a  2 s. c  o m
 * 
 * <pre>
 * SDCard
 * 
 * </pre>
 * 
 * @param context android.content.Context
 * @param dirName ???
 * @return APPapp_cache_path/dirName
 */
public static String getDiskCacheDir(Context context, String dirName) {
    String cachePath = null;
    if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
        File externalCacheDir = context.getExternalCacheDir();
        if (externalCacheDir != null) {
            cachePath = externalCacheDir.getPath();
        }
    }
    if (cachePath == null) {
        File cacheDir = context.getCacheDir();
        if (cacheDir != null && cacheDir.exists()) {
            cachePath = cacheDir.getPath();
        }
    }
    return cachePath + File.separator + dirName;
}

From source file:com.manning.androidhacks.hack037.MainActivity.java

private boolean canWriteInExternalStorage() {
    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 {//from   w ww. j a  va 2  s  .co m
        // 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;
    }

    return mExternalStorageAvailable && mExternalStorageWriteable;
}

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

/**
 * scan music in sdcard//from   www .  j a v  a  2  s . c om
 * 
 * @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
 *//*from  w w  w .  j a v  a2s.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:de.fmaul.android.cmis.utils.StorageUtils.java

public static File getStorageFile(Application app, String saveFolder, String filename) throws StorageException {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        StringBuilder builder = new StringBuilder();
        builder.append(saveFolder);/*from w w w . j a va 2s.co  m*/
        builder.append("/");
        builder.append(ROOT_FOLDER_APP);
        builder.append("/");
        builder.append(((CmisApp) app).getRepository().getServer().getName());
        if (filename != null) {
            builder.append("/");
            builder.append(filename);
        }
        return new File(builder.toString());
    } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        throw new StorageException("Storage in Read Only Mode");
    } else {
        throw new StorageException("Storage is unavailable");
    }
}