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:net.sileht.lullaby.Utils.java

public static void checkStorage() {
    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 w w.j  av a  2s.c om*/
        // 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;
    }
}

From source file:com.kg.emailalbum.mobile.util.CacheManager.java

/**
 * Get a cache directory for a specific task.
 * /* w  w w . j av a 2  s.co  m*/
 * @param subdir
 *            The name of the task, will result as a subdirectory of the
 *            cache root.
 * @return The cache directory for this task.
 */
public File getCacheDir(String subdir) {
    if (subdir == null) {
        subdir = "";
    }

    // Default root is the application context cache.
    File result = new File(mContext.getCacheDir(), subdir);

    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        // If an external storage is available, use it as it will prevent
        // from overloading the internal memory.
        result = new File(Environment.getExternalStorageDirectory(), "data/EmailAlbum/.cache/" + subdir);
    }

    // Physically create the directory (and its parents) if it does not
    // exist.
    if (!result.exists()) {
        result.mkdirs();
    }

    File noMedia = new File(result, ".nomedia");
    try {
        noMedia.createNewFile();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        Log.e(LOG_TAG, "Error : ", e);
    }

    // Log.i(LOG_TAG, "Using dir " + result + " for cache");
    return result;
}

From source file:ch.ethz.inf.vs.android.g54.a4.util.SnapshotCache.java

/**
 * Returns snapshot at index modulo the length of the list, if index is < 0, it returns a random snapshot
 *//*from w  w  w  . j ava2 s  .  com*/
private static List<WifiReading> getSnapshot(int index, Context c) {
    String state = Environment.getExternalStorageState();

    if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        // We can at least read the external storage
        File root = c.getExternalCacheDir();
        File[] snapshotFiles = root.listFiles(new FilenameFilter() {

            public boolean accept(File dir, String filename) {
                if (filename.endsWith(FILE_EXTENSION)) {
                    return true;
                } else {
                    return false;
                }
            }
        });
        if (snapshotFiles.length > 0) {
            if (index < 0) {
                Random rand = new Random();
                index = rand.nextInt(snapshotFiles.length);
            } else {
                index = index % snapshotFiles.length;
            }
            try {
                // read file into a string
                FileInputStream fstream = new FileInputStream(snapshotFiles[index]);
                Log.d(TAG, snapshotFiles[index].getName());
                DataInputStream in = new DataInputStream(fstream);
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                String fileContents = "";
                String strLine;
                while ((strLine = br.readLine()) != null) {
                    fileContents += strLine;
                }

                // make a json array out of the string
                JSONArray json = new JSONArray(fileContents);

                // parse the json array
                return jsonToReadings(json);
            } catch (Exception e) {
                Log.e(TAG, "Could not read file.");
                return null;
            }
        } else {
            // there are no cached snapshots
            return null;
        }
    } else {
        // we cannot read the external storage
        return null;
    }
}

From source file:fr.inria.ucn.collectors.LlamaCollector.java

@Override
public void run(Context c, long ts) {
    try {/*from ww w  . j  a  v a 2  s .  c o  m*/
        String state = Environment.getExternalStorageState();
        File llamaAreas = new File(Environment.getExternalStorageDirectory() + "/Llama/Llama_Areas.txt");

        if (Environment.MEDIA_MOUNTED.equals(state) && llamaAreas.exists()) {
            JSONObject data = new JSONObject();
            data.put("source_file", llamaAreas.toString());

            BufferedReader in = null;
            try {
                in = new BufferedReader(new FileReader(llamaAreas), 1024);
                String line;
                JSONObject a = new JSONObject();
                while ((line = in.readLine()) != null) {
                    String[] tmp = line.trim().split("\\|");
                    JSONArray wifi = new JSONArray();
                    JSONArray cell = new JSONArray();
                    for (int i = 1; i < tmp.length; i++) {
                        String[] tmp2 = tmp[i].split("\\:");
                        if (tmp2[0].trim().equalsIgnoreCase("W")) {
                            wifi.put(tmp2[1].trim());
                        } else {
                            // FIXME: figure out what these values are ?!?
                            JSONObject cid = new JSONObject();
                            cid.put("1", Integer.parseInt(tmp2[0].trim()));
                            cid.put("2", Integer.parseInt(tmp2[1].trim()));
                            cid.put("3", Integer.parseInt(tmp2[2].trim()));
                            cell.put(cid);
                        }
                    }
                    JSONObject o = new JSONObject();
                    o.put("wifi_networks", wifi); // wifi networks associated to this area
                    o.put("cells", cell); // cell ids associated to this area
                    a.put(tmp[0].trim(), o);
                }
                data.put("locations", a);

                // done
                Helpers.sendResultObj(c, "llama_location", ts, data);

            } catch (FileNotFoundException e) {
                Log.w(Constants.LOGTAG, "Llama exports not available", e);
            } catch (IOException e) {
                Log.w(Constants.LOGTAG, "Llama exports not available", e);
            }

            if (in != null)
                try {
                    in.close();
                } catch (IOException e) {
                }
        } else {
            Log.w(Constants.LOGTAG, "Llama exports not available, file=" + llamaAreas.toString() + ", exists="
                    + llamaAreas.exists());
        }

    } catch (JSONException jex) {
        Log.w(Constants.LOGTAG, "failed to create json object", jex);
    }
}

From source file:Main.java

public static File getSDDir(Context context) {
    if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
        // We can read and write the media
        return context.getExternalFilesDir(null);
    } else {//www.j a  va 2s  .c  o  m
        // Load another directory, probably local memory
        return context.getFilesDir();
    }
}

From source file:com.docd.purefm.test.CommandLineFileTest.java

@Override
protected void setUp() throws Exception {
    super.setUp();
    final String state = Environment.getExternalStorageState();
    if (!state.equals(Environment.MEDIA_MOUNTED)) {
        throw new RuntimeException(
                "Make sure the external storage is mounted read-write before running this test");
    }//from   w  ww . java 2  s. co m
    try {
        FileUtils.forceDelete(testDir);
    } catch (IOException e) {
        //ignored
    }
    assertTrue(testDir.mkdirs());

    // prepare a test file
    try {
        FileUtils.write(test1, "test");
    } catch (IOException e) {
        throw new RuntimeException("Failed to create test file: " + e);
    }
}

From source file:com.android.volley.cache.ACache.java

private static File getCacheDir(Context ctx) {
    File file = null;//w w  w  . j  a  v  a 2  s .c  o m
    try {
        boolean sdCardExist = Environment.getExternalStorageState()
                .equals(android.os.Environment.MEDIA_MOUNTED); //sd??
        if (sdCardExist) {
            file = new File(Environment.getExternalStorageDirectory(), VConstant.BASE_DIR);
        } else if (ctx != null) {
            file = ctx.getCacheDir();
        }
    } catch (Exception e) {
        file = new File(Environment.getExternalStorageDirectory(), VConstant.BASE_DIR);
    }

    //
    if (null != file && !file.exists()) {
        if (!file.mkdirs()) {
            throw new RuntimeException("can't make dirs dstravel/acache in " + file.getAbsolutePath());
        }
    }

    return file;
}

From source file:net.bible.android.view.activity.StartupActivity.java

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

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

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

    //See if any errors occurred during app initialisation, especially upgrade tasks
    int abortErrorMsgId = 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.goliathonline.android.kegbot.util.BitmapUtils.java

/**
 * Only call this method from the main (UI) thread. The {@link OnFetchCompleteListener} callback
 * be invoked on the UI thread, but image fetching will be done in an {@link AsyncTask}.
 *
 * @param cookie An arbitrary object that will be passed to the callback.
 *//*from  w w  w. ja va 2  s  .  c om*/
public static void fetchImage(final Context context, final String url,
        final BitmapFactory.Options decodeOptions, final Object cookie,
        final OnFetchCompleteListener callback) {
    new AsyncTask<String, Void, Bitmap>() {
        @Override
        protected Bitmap doInBackground(String... params) {
            final String url = params[0];
            if (TextUtils.isEmpty(url)) {
                return null;
            }

            // First compute the cache key and cache file path for this URL
            File cacheFile = null;
            try {
                MessageDigest mDigest = MessageDigest.getInstance("SHA-1");
                mDigest.update(url.getBytes());
                final String cacheKey = bytesToHexString(mDigest.digest());
                if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                    cacheFile = new File(Environment.getExternalStorageDirectory() + File.separator + "Android"
                            + File.separator + "data" + File.separator + context.getPackageName()
                            + File.separator + "cache" + File.separator + "bitmap_" + cacheKey + ".tmp");
                }
            } catch (NoSuchAlgorithmException e) {
                // Oh well, SHA-1 not available (weird), don't cache bitmaps.
            }

            if (cacheFile != null && cacheFile.exists()) {
                Bitmap cachedBitmap = BitmapFactory.decodeFile(cacheFile.toString(), decodeOptions);
                if (cachedBitmap != null) {
                    return cachedBitmap;
                }
            }

            try {
                // TODO: check for HTTP caching headers
                final HttpClient httpClient = SyncService.getHttpClient(context.getApplicationContext());
                final HttpResponse resp = httpClient.execute(new HttpGet(url));
                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);

                // Write response bytes to cache.
                if (cacheFile != null) {
                    try {
                        cacheFile.getParentFile().mkdirs();
                        cacheFile.createNewFile();
                        FileOutputStream fos = new FileOutputStream(cacheFile);
                        fos.write(respBytes);
                        fos.close();
                    } catch (FileNotFoundException e) {
                        Log.w(TAG, "Error writing to bitmap cache: " + cacheFile.toString(), e);
                    } catch (IOException e) {
                        Log.w(TAG, "Error writing to bitmap cache: " + cacheFile.toString(), e);
                    }
                }

                // Decode the bytes and return the bitmap.
                return BitmapFactory.decodeByteArray(respBytes, 0, respBytes.length, decodeOptions);
            } catch (Exception e) {
                Log.w(TAG, "Problem while loading image: " + e.toString(), e);
            }
            return null;
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            callback.onFetchComplete(cookie, result);
        }
    }.execute(url);
}

From source file:tw.idv.gasolin.pycontw2012.util.BitmapUtils.java

/**
 * Only call this method from the main (UI) thread. The
 * {@link OnFetchCompleteListener} callback be invoked on the UI thread, but
 * image fetching will be done in an {@link AsyncTask}.
 * //from  ww  w.  j a  v  a2 s  .co  m
 * @param cookie
 *            An arbitrary object that will be passed to the callback.
 */
public static void fetchImage(final Context context, final String url,
        final BitmapFactory.Options decodeOptions, final Object cookie,
        final OnFetchCompleteListener callback) {
    new AsyncTask<String, Void, Bitmap>() {
        @Override
        protected Bitmap doInBackground(String... params) {
            final String url = params[0];
            if (TextUtils.isEmpty(url)) {
                return null;
            }

            // First compute the cache key and cache file path for this URL
            File cacheFile = null;
            try {
                MessageDigest mDigest = MessageDigest.getInstance("SHA-1");
                mDigest.update(url.getBytes());
                final String cacheKey = bytesToHexString(mDigest.digest());
                if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                    cacheFile = new File(Environment.getExternalStorageDirectory() + File.separator + "Android"
                            + File.separator + "data" + File.separator + context.getPackageName()
                            + File.separator + "cache" + File.separator + "bitmap_" + cacheKey + ".tmp");
                }
            } catch (NoSuchAlgorithmException e) {
                // Oh well, SHA-1 not available (weird), don't cache
                // bitmaps.
            }

            if (cacheFile != null && cacheFile.exists()) {
                Bitmap cachedBitmap = BitmapFactory.decodeFile(cacheFile.toString(), decodeOptions);
                if (cachedBitmap != null) {
                    return cachedBitmap;
                }
            }

            try {
                // TODO: check for HTTP caching headers
                final HttpClient httpClient = SyncService.getHttpClient(context.getApplicationContext());
                final HttpResponse resp = httpClient.execute(new HttpGet(url));
                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);

                // Write response bytes to cache.
                if (cacheFile != null) {
                    try {
                        cacheFile.getParentFile().mkdirs();
                        cacheFile.createNewFile();
                        FileOutputStream fos = new FileOutputStream(cacheFile);
                        fos.write(respBytes);
                        fos.close();
                    } catch (FileNotFoundException e) {
                        Log.w(TAG, "Error writing to bitmap cache: " + cacheFile.toString(), e);
                    } catch (IOException e) {
                        Log.w(TAG, "Error writing to bitmap cache: " + cacheFile.toString(), e);
                    }
                }

                // Decode the bytes and return the bitmap.
                return BitmapFactory.decodeByteArray(respBytes, 0, respBytes.length, decodeOptions);
            } catch (Exception e) {
                Log.w(TAG, "Problem while loading image: " + e.toString(), e);
            }
            return null;
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            callback.onFetchComplete(cookie, result);
        }
    }.execute(url);
}