Java Code Examples for android.content.Context#getCacheDir()

The following examples show how to use android.content.Context#getCacheDir() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LibVLC.java    From Exoplayer_VLC with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize the libVLC class.
 *
 * This function must be called before using any libVLC functions.
 *
 * @throws LibVlcException
 */
public void init(Context context) throws LibVlcException {
    Log.v(TAG, "Initializing LibVLC");
    if (!mIsInitialized) {
        if(!LibVlcUtil.hasCompatibleCPU(context)) {
            Log.e(TAG, LibVlcUtil.getErrorMsg());
            throw new LibVlcException();
        }

        File cacheDir = context.getCacheDir();
        mCachePath = (cacheDir != null) ? cacheDir.getAbsolutePath() : null;
        nativeInit();
        setEventHandler(EventHandler.getInstance());
        mIsInitialized = true;
    }
}
 
Example 2
Source File: LogsHelper.java    From CommonUtils with Apache License 2.0 6 votes vote down vote up
public static boolean exportLogFiles(@NonNull Context context, @NonNull Intent intent) {
    try {
        File parent = new File(context.getCacheDir(), "logs");
        if (!parent.exists() && !parent.mkdir())
            return false;

        Process process = Runtime.getRuntime().exec("logcat -d");
        File file = new File(parent, "logs-" + System.currentTimeMillis() + ".txt");
        try (FileOutputStream out = new FileOutputStream(file, false)) {
            CommonUtils.copy(process.getInputStream(), out);
        } finally {
            process.destroy();
        }

        Uri uri = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".logs", file);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.putExtra(Intent.EXTRA_STREAM, uri);
        return true;
    } catch (IllegalArgumentException | IOException ex) {
        Log.e(TAG, "Failed exporting logs.", ex);
    }

    return false;
}
 
Example 3
Source File: OtherUtils.java    From android-open-project-demo with Apache License 2.0 6 votes vote down vote up
/**
 * @param context
 * @param dirName Only the folder name, not full path.
 * @return app_cache_path/dirName
 */
public static String getDiskCacheDir(Context context, String dirName) {
    String cachePath = null;
    if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
        File externalCacheDir = context.getExternalCacheDir();
        if (externalCacheDir != null) {
            cachePath = externalCacheDir.getPath();
        }
    }
    if (cachePath == null) {
        File cacheDir = context.getCacheDir();
        if (cacheDir != null && cacheDir.exists()) {
            cachePath = cacheDir.getPath();
        }
    }

    return cachePath + File.separator + dirName;
}
 
Example 4
Source File: FileUtils.java    From EnhancedScreenshotNotification with GNU General Public License v3.0 6 votes vote down vote up
@Nullable
public static File backupScreenshot(@NonNull Context context, @NonNull File file) {
    final File screenshotDir = new File(context.getCacheDir(), "screenshot");
    final File backupFile = new File(screenshotDir, file.getName());

    // Clear old files
    for (File oldFile : Optional.ofNullable(screenshotDir.listFiles()).orElse(new File[0])) {
        if (!oldFile.delete()) {
            Log.d("FileUtils", "Failed to delete " + oldFile.getAbsolutePath());
        }
    }

    // Start backup for sharing
    if (backupFile.exists() && !backupFile.delete()) {
        return null;
    } else if (!FileUtils.ensureDirectory(screenshotDir)) {
        return null;
    } else if (FileUtils.moveFile(file, backupFile)) {
        return backupFile;
    } else {
        return null;
    }
}
 
Example 5
Source File: AppCacheUtils.java    From v9porn with MIT License 5 votes vote down vote up
/**
 * 获取视频缓存目录
 *
 * @param context cotext
 * @return 缓存目录
 */
@NonNull
public static File getVideoCacheDir(Context context) {
    String path;
    if (SDCardUtils.isSDCardMounted()) {
        path = context.getExternalCacheDir() + VIDEO_CACHE_DIR;
    } else {
        path = context.getCacheDir() + VIDEO_CACHE_DIR;
    }
    File file = new File(path);
    if (!file.exists()) {
        file.mkdirs();
    }
    return file.getAbsoluteFile();
}
 
Example 6
Source File: FileLruCache.java    From FacebookImageShareIntent with MIT License 5 votes vote down vote up
public FileLruCache(Context context, String tag, Limits limits) {
    this.tag = tag;
    this.limits = limits;
    this.directory = new File(context.getCacheDir(), tag);
    this.lock = new Object();

    // Ensure the cache dir exists
    if (this.directory.mkdirs() || this.directory.isDirectory()) {
        // Remove any stale partially-written files from a previous run
        BufferFile.deleteAll(this.directory);
    }
}
 
Example 7
Source File: XulSystemUtil.java    From starcor.xul with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static String getInternalCacheDir(Context context) {
    File dir = context.getCacheDir();
    if (!dir.mkdirs() && !dir.exists()) {
        return null;
    }
    return dir.getPath();
}
 
Example 8
Source File: Volley.java    From SaveVolley with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it.
 *
 * @param context A {@link Context} to use for creating the cache dir.
 * @param stack An {@link HttpStack} to use for the network, or null for default.
 * @return A started {@link RequestQueue} instance.
 */
public static RequestQueue newRequestQueue(Context context, HttpStack stack) {
    File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);

    if (stack == null) {
        stack = new OkHttp3Stack(new OkHttpClient());
    }

    Network network = new BasicNetwork(stack);

    RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
    queue.start();

    return queue;
}
 
Example 9
Source File: HeifReader.java    From heifreader with MIT License 5 votes vote down vote up
/**
 * Initialize HeifReader module.
 *
 * @param context Context.
 */
public static void initialize(Context context) {
    mRenderScript = RenderScript.create(context);
    mCacheDir = context.getCacheDir();

    // find best HEVC decoder
    mDecoderName = null;
    mDecoderSupportedSize = new Size(0, 0);
    int numCodecs = MediaCodecList.getCodecCount();
    for (int i = 0; i < numCodecs; i++) {
        MediaCodecInfo codecInfo = MediaCodecList.getCodecInfoAt(i);
        if (codecInfo.isEncoder()) {
            continue;
        }
        for (String type : codecInfo.getSupportedTypes()) {
            if (type.equalsIgnoreCase(MediaFormat.MIMETYPE_VIDEO_HEVC)) {
                MediaCodecInfo.CodecCapabilities cap = codecInfo.getCapabilitiesForType(MediaFormat.MIMETYPE_VIDEO_HEVC);
                MediaCodecInfo.VideoCapabilities vcap = cap.getVideoCapabilities();
                Size supportedSize = new Size(vcap.getSupportedWidths().getUpper(), vcap.getSupportedHeights().getUpper());
                Log.d(TAG, "HEVC decoder=\"" + codecInfo.getName() + "\""
                        + " supported-size=" + supportedSize
                        + " color-formats=" + Arrays.toString(cap.colorFormats)
                );
                if (mDecoderSupportedSize.getWidth() * mDecoderSupportedSize.getHeight() < supportedSize.getWidth() * supportedSize.getHeight()) {
                    mDecoderName = codecInfo.getName();
                    mDecoderSupportedSize = supportedSize;
                }
            }
        }
    }
    if (mDecoderName == null) {
        throw new RuntimeException("no HEVC decoding support");
    }
    Log.i(TAG, "HEVC decoder=\"" + mDecoderName + "\" supported-size=" + mDecoderSupportedSize);
}
 
Example 10
Source File: MapboxSpeechPlayer.java    From graphhopper-navigation-android with MIT License 5 votes vote down vote up
private void setupCaches(Context context) {
  File okHttpDirectory = new File(context.getCacheDir(), OKHTTP_INSTRUCTION_CACHE);
  okHttpDirectory.mkdir();
  okhttpCache = new Cache(okHttpDirectory, TEN_MEGABYTE_CACHE_SIZE);
  mapboxCache = new File(context.getCacheDir(), MAPBOX_INSTRUCTION_CACHE);
  mapboxCache.mkdir();
}
 
Example 11
Source File: SavedWallpaperImages.java    From Trebuchet with GNU General Public License v3.0 5 votes vote down vote up
public static void moveFromCacheDirectoryIfNecessary(Context context) {
    // We used to store the saved images in the cache directory, but that meant they'd get
    // deleted sometimes-- move them to the data directory
    File oldSavedImagesFile = new File(context.getCacheDir(),
            LauncherFiles.WALLPAPER_IMAGES_DB);
    File savedImagesFile = context.getDatabasePath(LauncherFiles.WALLPAPER_IMAGES_DB);
    if (oldSavedImagesFile.exists()) {
        oldSavedImagesFile.renameTo(savedImagesFile);
    }
}
 
Example 12
Source File: LockScreenDeviceIconManager.java    From sdl_java_suite with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
LockScreenDeviceIconManager(Context context) {
    this.context = context;
    File lockScreenDirectory = new File(context.getCacheDir(), STORED_ICON_DIRECTORY_PATH);
    lockScreenDirectory.mkdirs();
}
 
Example 13
Source File: ACache.java    From HaoReader with GNU General Public License v3.0 4 votes vote down vote up
public static ACache get(Context ctx, String cacheName) {
	File f = new File(ctx.getCacheDir(), cacheName);
	return get(f, MAX_SIZE, MAX_COUNT);
}
 
Example 14
Source File: XCache.java    From XFrame with Apache License 2.0 4 votes vote down vote up
public static XCache get(Context ctx, long maxSize, int maxCount) {
    File f = new File(ctx.getCacheDir(), "XCache");
    return get(f, maxSize, maxCount);
}
 
Example 15
Source File: NativeAppCallAttachmentStore.java    From Abelana-Android with Apache License 2.0 4 votes vote down vote up
synchronized static File getAttachmentsDirectory(Context context) {
    if (attachmentsDirectory == null) {
        attachmentsDirectory = new File(context.getCacheDir(), ATTACHMENTS_DIR_NAME);
    }
    return attachmentsDirectory;
}
 
Example 16
Source File: PersistentBlobProvider.java    From deltachat-android with GNU General Public License v3.0 4 votes vote down vote up
private File getModernCacheFile(@NonNull Context context, long id) {
  return new File(context.getCacheDir(), "capture-m-" + id + "." + BLOB_EXTENSION);
}
 
Example 17
Source File: GRP.java    From react-native-get-real-path with MIT License 4 votes vote down vote up
public static String writeFile(Context context, Uri uri, String displayName) {
  InputStream input = null;
  try {
    input = context.getContentResolver().openInputStream(uri);
    /* save stream to temp file */
    try {
      File file = new File(context.getCacheDir(), displayName);
      OutputStream output = new FileOutputStream(file);
      try {
        byte[] buffer = new byte[4 * 1024]; // or other buffer size
        int read;

        while ((read = input.read(buffer)) != -1) {
          output.write(buffer, 0, read);
        }
        output.flush();

        final String outputPath = file.getAbsolutePath();
        return outputPath;

      } finally {
        output.close();
      }
    } catch (Exception e1a) {
      //
    } finally {
      try {
        input.close();
      } catch (IOException e1b) {
        //
      }
    }
  } catch (FileNotFoundException e2) {
    //
  } finally {
    if (input != null) {
      try {
        input.close();
      } catch (IOException e3) {
        //
      }
    }
  }

  return null;
}
 
Example 18
Source File: FileUtils.java    From AndroidPDF with Apache License 2.0 4 votes vote down vote up
public static File fileFromAsset(Context context, String assetName) throws IOException {
    File outFile = new File(context.getCacheDir(), assetName + "-pdfview.pdf");
    copy(context.getAssets().open(assetName), outFile);
    return outFile;
}
 
Example 19
Source File: CropUtil.java    From GalleryFinal with Apache License 2.0 4 votes vote down vote up
private static String getTempFilename(Context context) throws IOException {
    File outputDir = context.getCacheDir();
    File outputFile = File.createTempFile("image", "tmp", outputDir);
    return outputFile.getAbsolutePath();
}
 
Example 20
Source File: ACache.java    From tina with Apache License 2.0 4 votes vote down vote up
public static ACache get(Context ctx, String cacheName) {
	File f = new File(ctx.getCacheDir(), cacheName);
	return get(f, MAX_SIZE, MAX_COUNT);
}