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.eoidb.util.ImageDownloader.java

@SuppressWarnings("unchecked")
public void loadImageCache(Context context) {
    if (BuildConfig.DEBUG)
        Log.v(LOG_TAG, "Loading image cache...");
    File cacheFile = new File(context.getCacheDir(), cacheFileName);

    if (cacheFile.exists() && cacheFile.length() > 0) {
        ObjectInputStream ois = null;
        try {// www .  j  av  a 2  s. c  o  m
            HashMap<String, String> cacheDescription = new HashMap<String, String>();
            ois = new ObjectInputStream(new FileInputStream(cacheFile));
            cacheDescription = (HashMap<String, String>) ois.readObject();

            for (Entry<String, String> cacheDescEntry : cacheDescription.entrySet()) {
                loadSingleCacheFile(cacheDescEntry.getKey(), context);
            }
        } catch (StreamCorruptedException e) {
            Log.e(LOG_TAG, e.getMessage(), e);
        } catch (FileNotFoundException e) {
            Log.e(LOG_TAG, e.getMessage(), e);
        } catch (EOFException e) {
            //delete the corrupted cache file
            Log.w(LOG_TAG, "Deleting the corrupted cache file.", e);
            cacheFile.delete();
        } catch (IOException e) {
            Log.e(LOG_TAG, e.getMessage(), e);
        } catch (ClassNotFoundException e) {
            Log.e(LOG_TAG, e.getMessage(), e);
        } finally {
            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException e) {
                    Log.e(LOG_TAG, e.getMessage(), e);
                }
            }
        }
    }
}

From source file:com.github.mobile.util.HttpImageGetter.java

/**
 * Create image getter for context/*from   w  w  w .j  a  v a2  s  .  c  o  m*/
 *
 * @param context
 */
public HttpImageGetter(Context context) {
    this.context = context;
    dir = context.getCacheDir();

    WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    final Point size;
    if (Build.VERSION.SDK_INT < 13) {
        size = fetchDisplaySizePreHoneycomb(wm);
    } else {
        size = fetchDisplaySize(wm);
    }

    width = size.x;
    height = size.y;

    loadedBitmaps = new ArrayList<>();
    loading = new LoadingImageGetter(context, 24);
}

From source file:com.lillicoder.newsblurry.util.FileLogger.java

/**
 * Gets a {@link File} object for the given filename. If the indicated
 * file already exists, it will be overwritten by a new file. The returned file 
 * lives in this app's external cache directory by default (when external
 * media is not available, the internal cache is used instead).
 * @param filename Filename of the file to get.
 * @return {@link File} object for the given filename.
 */// w w w . j a va  2  s .  c o  m
private File getLogFile(String filename) {
    Assert.assertTrue(!TextUtils.isEmpty(filename));

    // Use cache directory so that files are removed on uninstall.
    Context context = this.getContext();

    // Check for external media availability. If available,
    // write to that directory. Otherwise get the internal cache
    // directory and write there.
    File rootDirectory;
    if (this.isExternalStorageAvailable())
        rootDirectory = context.getExternalCacheDir();
    else
        rootDirectory = context.getCacheDir();

    // If the file to write already exists, delete it.
    File logFile = new File(rootDirectory, filename);
    if (logFile.exists())
        logFile.delete();

    return logFile;
}

From source file:org.ado.minesync.minecraft.MinecraftWorldManager.java

public MinecraftWorldManager(DbxAccountManager dbxAccountManager, Context context) {
    notNull(dbxAccountManager, "dbxAccountManager cannot be null");
    notNull(context, "context cannot be null");

    dropboxFileManager = new DropboxFileManager(dbxAccountManager, context.getCacheDir());
    mineSyncWorldStatus = new MineSyncWorldStatus(context.getApplicationContext());
    dbHelper = MineSyncDbOpenHelper.getInstance(context);
    jsonWorldManager = new JsonWorldManager(context);
    zipArchiver = new ZipArchiver();
    minecraftData = new MinecraftData();
    tmpDirectory = context.getCacheDir();
    this.context = context;
}

From source file:com.bullmobi.base.ui.fragments.dialogs.FeedbackDialog.java

private void attachLog(@NonNull Intent intent) {
    Context context = getActivity();

    try {//  w  w w .  j a v  a2  s  .  c  o m
        String log = Logcat.capture();
        if (log == null)
            throw new Exception("Failed to capture the logcat.");

        // Prepare cache directory.
        File cacheDir = context.getCacheDir();
        if (cacheDir == null)
            throw new Exception("Cache directory is inaccessible");
        File directory = new File(cacheDir, LogsProviderBase.DIRECTORY);
        FileUtils.deleteRecursive(directory); // Clean-up cache folder
        if (!directory.mkdirs())
            throw new Exception("Failed to create cache directory.");

        // Create log file.
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        String fileName = "EasyNotification_log_" + sdf.format(new Date()) + ".txt";
        File file = new File(directory, fileName);

        // Write to the file.
        if (!FileUtils.writeToFile(file, log))
            throw new Exception("Failed to write log to the file.");

        // Put extra stream to the intent.
        Uri uri = Uri.parse("content://" + LogAttachmentProvider.AUTHORITY + "/" + fileName);
        intent.putExtra(Intent.EXTRA_STREAM, uri);
    } catch (Exception e) {
        String message = ResUtils.getString(getResources(), R.string.feedback_error_accessing_log,
                e.getMessage());
        ToastUtils.showLong(context, message);
    }
}

From source file:com.achep.base.ui.fragments.dialogs.FeedbackDialog.java

private void attachLog(@NonNull Intent intent) {
    Context context = getActivity();

    try {// w w  w. java2  s  .  c o  m
        String log = Logcat.capture();
        if (log == null)
            throw new Exception("Failed to capture the logcat.");

        // Prepare cache directory.
        File cacheDir = context.getCacheDir();
        if (cacheDir == null)
            throw new Exception("Cache directory is inaccessible");
        File directory = new File(cacheDir, LogsProviderBase.DIRECTORY);
        FileUtils.deleteRecursive(directory); // Clean-up cache folder
        if (!directory.mkdirs())
            throw new Exception("Failed to create cache directory.");

        // Create log file.
        @SuppressLint("SimpleDateFormat")
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        String fileName = "AcDisplay_log_" + sdf.format(new Date()) + ".txt";
        File file = new File(directory, fileName);

        // Write to the file.
        if (!FileUtils.writeToFile(file, log))
            throw new Exception("Failed to write log to the file.");

        // Put extra stream to the intent.
        Uri uri = Uri.parse("content://" + LogAttachmentProvider.AUTHORITY + "/" + fileName);
        intent.putExtra(Intent.EXTRA_STREAM, uri);
    } catch (Exception e) {
        String message = ResUtils.getString(getResources(), R.string.feedback_error_accessing_log,
                e.getMessage());
        ToastUtils.showLong(context, message);
    }
}

From source file:com.hybris.mobile.lib.http.manager.volley.VolleyPersistenceManager.java

/**
 * This method create a new RequestQueue that returns the callbacks in a background thread and not the UI thread
 *
 * @param context          the android context
 * @param sslSocketFactory the SSL factory for the calls
 * @return the RequestQueue created/*from w  w  w  .  ja  va 2  s .  c o m*/
 */
protected RequestQueue newRequestQueueBackgroundThread(Context context, SSLSocketFactory sslSocketFactory) {
    // This code comes from the official volley library
    File cacheDir = new File(context.getCacheDir(), "volley");

    String userAgent = "volley/0";
    try {
        String packageName = context.getPackageName();
        PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
        userAgent = packageName + "/" + info.versionCode;
    } catch (PackageManager.NameNotFoundException e) {
        Log.e(TAG, userAgent + " : " + e.getMessage());

    }

    Network network = new BasicNetwork(new HurlStack(null, sslSocketFactory));

    // This code allows the callback to be returned in a background thread and not the UI thread
    ResponseDelivery responseDelivery = new ExecutorDelivery(Executors.newFixedThreadPool(THREAD_POOL_SIZE));
    RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network, THREAD_POOL_SIZE,
            responseDelivery);
    queue.start();

    return queue;
}

From source file:com.hunch.ImageManager.java

protected void addToApplicationCache(Bitmap d, URL url, Context context) {
    final String fileName = fileNameFromURL(url);
    File cachedImagesDir = new File(context.getCacheDir(), Const.CACHE_IMG_DIR);

    if (!cachedImagesDir.exists()) {
        cachedImagesDir.mkdir();//  w w  w .ja  va2  s .  c  o m
    }

    File imageFile = new File(cachedImagesDir, fileName);

    /*if( !imageFile.canWrite() )
    {
       Log.w( Const.TAG, "can't write to app image cache! (" + imageFile.toString() + ")" );
       return;
    }*/

    FileOutputStream fOut = null;
    try {
        fOut = new FileOutputStream(imageFile);

    } catch (FileNotFoundException e) {
        Log.w(Const.TAG, "can't find or write to file in app cache! (" + imageFile.getAbsolutePath() + ")");
        e.printStackTrace();
        return;
    }

    boolean success = d.compress(Bitmap.CompressFormat.PNG, 0, fOut);
    if (!success) {
        Log.w(Const.TAG, "image compress for app cache failed! (" + imageFile.getAbsolutePath() + ")");
    }

    try {
        fOut.flush();
        fOut.close();
    } catch (IOException e) {
        Log.w(Const.TAG,
                "couldn't flush or close output stream for app cache! (" + imageFile.getAbsolutePath() + ")");
    }
}

From source file:com.facebook.FileLruCache.java

FileLruCache(Context context, String tag, Limits limits) {
    this.tag = tag;
    this.limits = limits;
    this.directory = new File(context.getCacheDir(), tag);

    // Ensure the cache dir exists
    this.directory.mkdirs();

    // Remove any stale partially-written files from a previous run
    BufferFile.deleteAll(this.directory);
}

From source file:com.hunch.ImageManager.java

protected FileInputStream getImageFileStreamFromCache(final Context context, final URL url) {
    final String fileName = fileNameFromURL(url);

    File hunchCacheDir = new File(context.getCacheDir(), Const.CACHE_IMG_DIR);
    File[] imageFileList = hunchCacheDir.listFiles(new FilenameFilter() {

        @Override//from w  w w  . j  a v a2s.c o  m
        public boolean accept(File dir, String aFilename) {
            return aFilename.equals(fileName);
        }
    });

    if (imageFileList == null || imageFileList.length == 0) {
        return null;
    }

    if (imageFileList.length > 1) {
        Log.i(Const.TAG,
                "found " + imageFileList.length + " images for url in app cache! " + "(" + fileName + ")");
    }

    FileInputStream iStream = null;
    try {
        iStream = new FileInputStream(imageFileList[0]);
    } catch (FileNotFoundException e) {
        return null;
    }

    //Log.v( Const.TAG, "found image in app cache (" + url + ")" );

    return iStream;
}