List of usage examples for android.os Environment getExternalStorageState
public static String getExternalStorageState()
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 om*/ 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:com.phonegap.DirectoryManager.java
/** * Determine if SD card exists./*from www .j a va 2 s .c om*/ * * @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:net.bible.android.view.activity.StartupActivity.java
/** Called when the activity is first created. */ @Override/*from w w w . ja va 2 s. c o m*/ 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. *//* w w w . j a v a 2s. 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}. * // ww w .j av a2s.com * @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); }
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;// w w w.j a v a2s .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 www . j a v a2 s . co m*/ * * @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 av a2s .com * @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 ww . j a v a 2s .c o m 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 www . j ava2s . c o m*/ throw new StorageException("Storage is unavailable"); } }