Example usage for android.content Context getCacheDir

List of usage examples for android.content Context getCacheDir

Introduction

In this page you can find the example usage for android.content Context getCacheDir.

Prototype

public abstract File getCacheDir();

Source Link

Document

Returns the absolute path to the application specific cache directory on the filesystem.

Usage

From source file:com.amytech.android.library.utils.asynchttp.FileAsyncHttpResponseHandler.java

/**
 * Used when there is no file to be used when calling constructor
 *
 * @param context/*from   ww w . j a  va2  s.  c o m*/
 *            Context, must not be null
 * @return temporary file or null if creating file failed
 */
protected File getTemporaryFile(Context context) {
    Utils.asserts(context != null, "Tried creating temporary file without having Context");
    try {
        // not effective in release mode
        assert context != null;
        return File.createTempFile("temp_", "_handled", context.getCacheDir());
    } catch (IOException e) {
        Log.e(LOG_TAG, "Cannot create temporary file", e);
    }
    return null;
}

From source file:com.raptureinvenice.webimageview.cache.WebImageCache.java

public void addBitmapToCache(Context context, String urlString, Bitmap bitmap) {
    // mem cache/*from  w w  w.j a va2 s . co m*/
    addBitmapToMemCache(urlString, bitmap);

    // disk cache
    // TODO: manual cache cleanup
    if (mIsDiskCachingEnabled) {
        File path = context.getCacheDir();
        OutputStream os = null;
        String hashedURLString = hashURLString(urlString);

        try {
            // NOWORKY File tmpFile = File.createTempFile("wic.", null);
            File file = new File(path, hashedURLString);
            os = new FileOutputStream(file.getAbsolutePath());

            bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
            os.flush();
            os.close();

            // NOWORKY tmpFile.renameTo(file);
        } catch (Exception ex) {
            Log.e(TAG, "Could not store " + urlString + " to disk cache: " + ex.toString());
        } finally {
            try {
                os.close();
            } catch (Exception ex) {
            }
        }
    }
}

From source file:in.rab.ordboken.Ordboken.java

private Ordboken(Context context) {
    mContext = context;/*from w w w .ja  va2  s .  c  o m*/

    try {
        // Ends up only fully caching the search results. Documents use ETag
        // and are conditionally cached.
        HttpResponseCache.install(new File(context.getCacheDir(), "ordboken"), 1024 * 1024);
    } catch (IOException e) {
        // Oh well...
    }

    mPrefs = context.getSharedPreferences("ordboken", Context.MODE_PRIVATE);
    mLastWhere = Where.valueOf(mPrefs.getString("lastWhere", Where.MAIN.toString()));
    mLastWhat = mPrefs.getString("lastWhat", "ordbok");

    mConnMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    mNeClient = new NeClient(NeClient.Auth.BASIC);
    mNeClient.setPersistentAuthData(mPrefs.getString("persistentAuthData", null));
    mNeClient.setUsername(mPrefs.getString("username", null));
    mNeClient.setPassword(mPrefs.getString("password", null));
}

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;/*  w  w w  .  ja  v  a  2s . c  o 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;
}

From source file:at.modalog.cordova.plugin.cache.Cache.java

@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    /*try// w w w. j av a2s. c om
    {
    */
    if (action.equals("clear")) {
        Log.v(LOG_TAG, "Cordova Android Cache.clear() called.");
        this.callbackContext = callbackContext;

        final Cache self = this;
        final Context ctx = this.cordova.getActivity().getApplicationContext();
        cordova.getActivity().runOnUiThread(new Runnable() {
            public void run() {
                try {
                    // clear the cache
                    self.webView.clearCache(true);
                    File dir = ctx.getCacheDir();
                    deleteDir(dir);

                    // send success result to cordova
                    PluginResult result = new PluginResult(PluginResult.Status.OK);
                    result.setKeepCallback(false);
                    self.callbackContext.sendPluginResult(result);
                } catch (Exception e) {
                    String msg = "Error while clearing webview cache.";
                    Log.e(LOG_TAG, msg);

                    // return error answer to cordova
                    PluginResult result = new PluginResult(PluginResult.Status.ERROR, msg);
                    result.setKeepCallback(false);
                    self.callbackContext.sendPluginResult(result);
                }
            }
        });
        return true;
    }
    return false;
    /*
    }
    catch (JSONException e)
    {
    // TODO: signal JSON problem to JS
    //callbackContext.error("Problem with JSON");
    return false;
    }
    */
}

From source file:fr.eoidb.util.ImageDownloader.java

private void flushSingleCacheFileToDisk(Bitmap bitmap, String cacheIconName, Context context)
        throws IOException {
    File cacheIconFile = new File(context.getCacheDir(), cacheIconName);
    if (!cacheIconFile.exists()) {
        if (BuildConfig.DEBUG)
            Log.v(LOG_TAG, "Flushing bitmap " + cacheIconName + " to disk...");
        cacheIconFile.createNewFile();/* w w  w .  ja va2  s .  com*/

        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(cacheIconFile));
        bitmap.compress(CompressFormat.PNG, 100, bos);
        bos.flush();
        bos.close();
    }
}

From source file:fr.eoidb.util.ImageDownloader.java

private Bitmap loadSingleCacheFile(String url, Context context) {
    Bitmap bitmap = null;/*  ww  w .j a  v  a2 s  .co  m*/
    File cacheIconFile = new File(context.getCacheDir(), getCacheFileName(url));
    if (cacheIconFile.exists()) {
        if (BuildConfig.DEBUG)
            Log.v(LOG_TAG, "Loading cache file : " + url);

        bitmap = BitmapFactory.decodeFile(cacheIconFile.getAbsolutePath());

        if (bitmap != null) {
            sHardBitmapCache.put(url, bitmap);
        }
    }

    return bitmap;
}

From source file:org.kontalk.util.MediaStorage.java

/**
 * Tries various methods for obtaining the rotation of the image.
 * @return a matrix to rotate the image (if any)
 *//* w w w .  j  av a2 s. c  o m*/
private static Matrix getRotation(Context context, Uri media) throws IOException {
    // method 1: query the media storage
    Cursor cursor = context.getContentResolver().query(media,
            new String[] { MediaStore.Images.ImageColumns.ORIENTATION }, null, null, null);

    if (cursor != null) {
        cursor.moveToFirst();
        int orientation = cursor.getInt(0);
        cursor.close();

        if (orientation != 0) {
            Matrix m = new Matrix();
            m.postRotate(orientation);

            return m;
        }
    }

    // method 2: write media contents to a temporary file and run ExifInterface
    InputStream in = context.getContentResolver().openInputStream(media);
    OutputStream out = null;
    File tmp = null;
    try {
        tmp = File.createTempFile("rotation", null, context.getCacheDir());
        out = new FileOutputStream(tmp);

        SystemUtils.copy(in, out);
        // flush the file
        out.close();

        ExifInterface exif = new ExifInterface(tmp.toString());
        int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
        Matrix matrix = new Matrix();
        switch (orientation) {
        case ExifInterface.ORIENTATION_ROTATE_90:
            matrix.postRotate(90);
            break;
        case ExifInterface.ORIENTATION_ROTATE_180:
            matrix.postRotate(180);
            break;
        case ExifInterface.ORIENTATION_ROTATE_270:
            matrix.postRotate(270);
            break;
        default:
            return null;
        }

        return matrix;
    } finally {
        if (tmp != null)
            tmp.delete();
        SystemUtils.closeStream(in);
        SystemUtils.closeStream(out);
    }
}

From source file:com.android.settings.users.EditUserPhotoController.java

private Uri createTempImageUri(Context context, String fileName, boolean purge) {
    final File folder = context.getCacheDir();
    folder.mkdirs();//from w w  w.  j  a  v a2 s  . com
    final File fullPath = new File(folder, fileName);
    if (purge) {
        fullPath.delete();
    }
    return FileProvider.getUriForFile(context, RestrictedProfileSettings.FILE_PROVIDER_AUTHORITY, fullPath);
}

From source file:fr.sedona.volley.manager.HttpImageLoader.java

@SuppressLint("NewApi")
private long getDiskCacheSpace(Context context) {
    String cachePath = context.getCacheDir().getPath();
    File diskCacheDir = new File(cachePath);

    if (Build.VERSION.SDK_INT >= 9) {
        return Math.min(diskCacheDir.getFreeSpace() - (1024 * 1024 * 30), (long) 1024 * 1024 * 20);
    }//from   www .  j  av a 2 s.  c om
    StatFs statFs = new StatFs(diskCacheDir.getAbsolutePath());
    return (long) Math.min(statFs.getAvailableBlocks() * (long) statFs.getBlockSize() - (1024 * 1024 * 30),
            (long) 1024 * 1024 * 20);
}