下面列出了android.content.Context#getCacheDir ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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;
}
/**
* @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;
}
@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;
}
}
/**
* 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;
}
}
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();
}
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);
}
}
private static String getInternalCacheDir(Context context) {
File dir = context.getCacheDir();
if (!dir.mkdirs() && !dir.exists()) {
return null;
}
return dir.getPath();
}
/**
* 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;
}
/**
* 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);
}
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);
}
}
/**
* 获取视频缓存目录
*
* @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();
}
public static ACache get(Context ctx, String cacheName) {
File f = new File(ctx.getCacheDir(), cacheName);
return get(f, MAX_SIZE, MAX_COUNT);
}
private static String getTempFilename(Context context) throws IOException {
File outputDir = context.getCacheDir();
File outputFile = File.createTempFile("image", "tmp", outputDir);
return outputFile.getAbsolutePath();
}
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;
}
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;
}
LockScreenDeviceIconManager(Context context) {
this.context = context;
File lockScreenDirectory = new File(context.getCacheDir(), STORED_ICON_DIRECTORY_PATH);
lockScreenDirectory.mkdirs();
}
private File getModernCacheFile(@NonNull Context context, long id) {
return new File(context.getCacheDir(), "capture-m-" + id + "." + BLOB_EXTENSION);
}
synchronized static File getAttachmentsDirectory(Context context) {
if (attachmentsDirectory == null) {
attachmentsDirectory = new File(context.getCacheDir(), ATTACHMENTS_DIR_NAME);
}
return attachmentsDirectory;
}
public static XCache get(Context ctx, long maxSize, int maxCount) {
File f = new File(ctx.getCacheDir(), "XCache");
return get(f, maxSize, maxCount);
}
public static ACache get(Context ctx, String cacheName) {
File f = new File(ctx.getCacheDir(), cacheName);
return get(f, MAX_SIZE, MAX_COUNT);
}