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:fr.shywim.antoinedaniel.utils.Utils.java

/**
 * Delete the application's cache directory.
 *
 * @param context application's context//  w ww.  jav a2 s . c  o  m
 * @return whether the directory has been successfully deleted or not
 */
public static boolean deleteCacheDir(Context context) {
    try {
        File dir = context.getCacheDir();
        if (dir != null && dir.isDirectory()) {
            return deleteDir(dir);
        }
    } catch (Exception e) {
        Crashlytics.logException(e);
    }
    return false;
}

From source file:Main.java

public static File getCacheDirectory(Context context, boolean preferExternal, String dirName) {
    File appCacheDir = null;// w w  w .j a v a 2s. c  o  m
    if (preferExternal && MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
            && hasExternalStoragePermission(context)) {
        appCacheDir = getExternalCacheDir(context, dirName);
        Log.e("appCacheDir", appCacheDir.toString());
    }
    if (appCacheDir == null) {
        appCacheDir = context.getCacheDir();
    }
    if (appCacheDir == null) {
        String cacheDirPath = "/data/data/" + context.getPackageName() + "/cache/";
        //Log.w("Can't define system cache directory! '%s' will be used.",cacheDirPath);
        appCacheDir = new File(cacheDirPath);
    }
    return appCacheDir;
}

From source file:edu.hastings.hastingscollege.MainActivity.java

public static void trimCache(Context context) {
    try {/*from ww w  .ja va  2 s.  c  o m*/
        File dir = context.getCacheDir();
        if (dir != null && dir.isDirectory()) {
            deleteDir(dir);
        }
    } catch (Exception e) {
        Log.v("Trim Cache exception", e.toString());
    }
}

From source file:Main.java

/**
 * Returns specified application cache directory. Cache directory will be created on SD card by defined path if card
 * is mounted and app has appropriate permission. Else - Android defines cache directory on device's file system.
 *
 * @param context  Application context/*from  ww w.  jav a 2 s  .  c  o  m*/
 * @param cacheDir Cache directory path (e.g.: "AppCacheDir", "AppDir/cache/images")
 * @return Cache {@link File directory}
 */
public static File getOwnCacheDirectory(Context context, String cacheDir, boolean preferExternal) {
    File appCacheDir = null;
    if (preferExternal && MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
            && hasExternalStoragePermission(context)) {
        appCacheDir = new File(Environment.getExternalStorageDirectory(), cacheDir);
    }
    if (appCacheDir == null || (!appCacheDir.exists() && !appCacheDir.mkdirs())) {
        appCacheDir = context.getCacheDir();
    }
    return appCacheDir;
}

From source file:io.nuclei.splice.internal.FileManager.java

private static File getBaseFile(Context context, int type) throws IOException {
    File base = null;/*from  ww  w  .java  2 s  . c  o  m*/
    if (type == TYPE_EXTERNAL_FILE && Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()))
        base = new File(context.getExternalFilesDir(null), DIR);
    else if (type == TYPE_CACHE_FILE)
        base = new File(context.getCacheDir(), DIR);
    else if (type == TYPE_LOCAL_FILE)
        base = new File(context.getFilesDir(), DIR);
    if (base == null)
        throw new IOException("Couldn't access directory type: " + type);
    if (!base.exists() && !base.mkdirs())
        throw new IOException("Couldn't create directory: " + base);
    return base;
}

From source file:org.stenerud.kscrash.KSCrashInstallationEmail.java

private static List<KSCrashReportFilter> generateFilters(Context context, List<String> recipients,
        String subject, String message) {
    List<KSCrashReportFilter> reportFilters = new LinkedList<KSCrashReportFilter>();
    reportFilters.add(new KSCrashReportFilterJSONEncode(4));
    reportFilters.add(new KSCrashReportFilterGZipCompress());
    reportFilters.add(/*  www  . j  a  v a  2s .c o m*/
            new KSCrashReportFilterCreateTempFiles(new File(context.getCacheDir(), "temp"), "report", "gz"));
    reportFilters.add(new KSCrashReportFilterEmail(context, recipients, subject, message));
    reportFilters.add(new KSCrashReportFilterDeleteFiles());

    return reportFilters;
}

From source file:net.henryco.opalette.api.utils.Utils.java

public static void shareBitmapAction(Bitmap bitmap, String filename, Context activity, boolean saveAfter,
        Runnable... runnables) {// w ww.j  a  v a 2  s  .  c  o m

    String file_name = filename;
    if (!file_name.endsWith(".png"))
        file_name += ".png";

    try {
        File cachePath = new File(activity.getCacheDir(), "images"); // see: res/xml/filepaths.xml

        if (cachePath.exists())
            deleteRecursive(cachePath);
        cachePath.mkdirs();

        FileOutputStream stream = new FileOutputStream(cachePath + "/" + file_name);
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        stream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    File imagePath = new File(activity.getCacheDir(), "images");
    File newFile = new File(imagePath, file_name);
    Uri contentUri = FileProvider.getUriForFile(activity, "net.henryco.opalette.fileprovider", newFile);

    if (contentUri != null) {
        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // temp permission for receiving app to read this file
        shareIntent.setType("image/png");
        shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri);
        activity.startActivity(Intent.createChooser(shareIntent, "Share"));
    }
    if (saveAfter)
        saveBitmapAction(bitmap, filename, activity, runnables);
}

From source file:at.ac.uniklu.mobile.sportal.util.Utils.java

/**
 * Loads a bitmap for the network or from a cached file, if it has already been downloaded before. If the file
 * is loaded for the first time, it is written to the cache to be available next time.
 * /*  w  w  w  . j av a 2 s.c om*/
 * @param context
 * @param sourceUrl
 * @param cacheFileName
 * @return a bitmap or null if something went wrong
 */
public static Bitmap downloadBitmapWithCache(Context context, String sourceUrl, String cacheFileName)
        throws Exception {
    Bitmap bitmap = null;
    File cacheFile = new File(context.getCacheDir(), cacheFileName);

    boolean cached = cacheFile.exists();
    boolean cachedValid = cached && cacheFile.lastModified() > (System.currentTimeMillis() - MILLIS_PER_WEEK);

    if (cached && cachedValid) {
        // the requested file is cached, load it
        Log.d(TAG, "loading cached file: " + cacheFileName);
        bitmap = BitmapFactory.decodeFile(cacheFile.getAbsolutePath());
    } else {
        // the requested file is not cached, download it from the network
        Log.d(TAG, "file " + (cachedValid ? "too old" : "not cached") + ", downloading: " + sourceUrl);
        byte[] data = downloadFile(sourceUrl, 3);
        if (data != null) {
            bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
            if (bitmap != null) {
                // the download succeeded, cache the file so it is available next time
                FileOutputStream out = new FileOutputStream(cacheFile);
                out.write(data, 0, data.length);
                out.flush();
                out.close();
            } else {
                Log.e(TAG, "failed to download bitmap, may be an unsupported format: " + sourceUrl);
            }
        }
    }

    return bitmap;
}

From source file:com.conferenceengineer.android.iosched.util.ImageLoader.java

/**
 * Get a usable cache directory (external if available, internal otherwise).
 *
 * @param context The context to use//from   w  w w . ja va  2  s  . co m
 * @param uniqueName A unique directory name to append to the cache dir
 * @return The cache dir
 */
public static File getDiskCacheDir(Context context, String uniqueName) {
    // TODO: getCacheDir() should be moved to a background thread as it attempts to create the
    // directory if it does not exist (no disk access should happen on the main/UI thread).
    final String cachePath = context.getCacheDir().getPath();
    return new File(cachePath + File.separator + uniqueName);
}

From source file:Main.java

public static File getCacheDir(Context context) {
    Log.i("getCacheDir", "cache sdcard state: " + Environment.getExternalStorageState());
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        File cacheDir = context.getExternalCacheDir();
        if (cacheDir != null && (cacheDir.exists() || cacheDir.mkdirs())) {
            Log.i("getCacheDir", "cache dir: " + cacheDir.getAbsolutePath());
            return cacheDir;
        }//from   w  ww. j  a  v a  2s.com
    }

    File cacheDir = context.getCacheDir();
    Log.i("getCacheDir", "cache dir: " + cacheDir.getAbsolutePath());

    return cacheDir;
}