When to clear cache in Android?

I have an application that displays images from the Internet (a showcase for a designer). I started caching my content in the internal cache directory, but the content of the application can take about 150 MB in cache size. And what docs for android say:

You should always store the cache files yourself and stay within a reasonable limit of space consumption, for example 1 MB. When a user uninstalls your application, these files are deleted.

So, I looked at the Currents application (Galaxy Nexus), and the cache size for the application is 110 MB. But what is strange is that applications such as Google Currents and Google Maps cache the contents in the name (USB storage data):

enter image description here

So what is this β€œUSB storage data" that the previous application uses. And if you implement caching in your application, do you iterate over all your application files in the cache to get the size every time you need to insert something, and then compare and clear it? Or do you continue to cache the content until Android decides to spend time cleaning the application directory?

I am very interested to know what the cache control flow in Android is, or at least what other applications do with great caching content.

+69
android caching
Mar 30 2018-12-12T00:
source share
5 answers

Before moving on to your question, we briefly explain two types of storage:

Cache

This is a folder specific to the application on the file system. The purpose of this directory is to store temporary data that your application may need for sessions between sessions, but it is not necessary to have them forever. You usually access this directory with Context.getCacheDir() . This will appear as a "cache" in the settings of your application.

Files

Like the cache folder, your application also has a directory of applications for storing files. Files in this directory will exist until the application explicitly deletes them or the application is deleted. You typically access this directory using Context.getFilesDir() . This may appear as various things on the application information screen, but in your screenshot this is β€œUSB storage data”.

NOTE. If you want to explicitly place it on an external medium (usually an SD card), you can use Context.getExternalFilesDir(String type) . p>

Difference

Both directories are specific to your application only (other applications do not have access). One of the differences between the cache directory and the files is that if the system becomes smaller on storage, the first place it is going to free resources belongs to your cache directory. The system will not clear data from the file directory. Another difference is that the cache directory can usually be cleared manually from the application information screen. Normally, the file directory can also work, but clearing the file directory also clears the cache directory.

Which one am I using?

It depends on how important the data is compared to the lifetime of your application. If you only need data for one session, and you doubt that you will ever need to use this data again, then do not use it. Just keep it in your memory until you need it. If you suspect that you will need to reuse data between multiple sessions, but do not need to keep a paper copy, use the cache directory. If you must have this data no matter what, or if it is quite large data that requires permanent storage, use the file directory. Here are some examples I can think of:

  • Cache - Recently Opened Email
    • After opening, cache the data, so when the user wants to read this email again, he downloads instantly, instead of using the network again to get the same data. I do not need to keep this forever, because ultimately the user will be finished by email.
  • Files - an application downloaded from email
    • This is the action of a user who says "I want to save this data so that I can restore it when I need it." So put it in the file directory as I never want to delete this file until the user wants to delete it.

When do I need to clear the cache directory?

From Context.getCacheDir() javadocs:

Note. You should not rely on a system deleting these files for you; you should always have a reasonable maximum, for example 1 MB, for the amount of space that you consume with cache files, and trim these files when this space is exceeded.

It uses an example of 1 MB, but may or may not be reasonable for your application. Despite this, you need to set a hard maximum. The reason for this comes down to developing a responsible application. So when should you check? I would recommend checking every time you want to put something in the cache directory. Here's a very simple cache manager:

 public class CacheManager { private static final long MAX_SIZE = 5242880L; // 5MB private CacheManager() { } public static void cacheData(Context context, byte[] data, String name) throws IOException { File cacheDir = context.getCacheDir(); long size = getDirSize(cacheDir); long newSize = data.length + size; if (newSize > MAX_SIZE) { cleanDir(cacheDir, newSize - MAX_SIZE); } File file = new File(cacheDir, name); FileOutputStream os = new FileOutputStream(file); try { os.write(data); } finally { os.flush(); os.close(); } } public static byte[] retrieveData(Context context, String name) throws IOException { File cacheDir = context.getCacheDir(); File file = new File(cacheDir, name); if (!file.exists()) { // Data doesn't exist return null; } byte[] data = new byte[(int) file.length()]; FileInputStream is = new FileInputStream(file); try { is.read(data); } finally { is.close(); } return data; } private static void cleanDir(File dir, long bytes) { long bytesDeleted = 0; File[] files = dir.listFiles(); for (File file : files) { bytesDeleted += file.length(); file.delete(); if (bytesDeleted >= bytes) { break; } } } private static long getDirSize(File dir) { long size = 0; File[] files = dir.listFiles(); for (File file : files) { if (file.isFile()) { size += file.length(); } } return size; } } 

Of course, this can be an expensive operation, so you should plan on caching in the background thread.

In addition, it can be as difficult as you need. In my example, I assume that all cached files are located in the root of the cache directory, so I do not check for potential subdirectories. The process of deleting files can also become more complicated, for example, deleting files by the oldest access date.

One thing to keep in mind when deciding on data caching is that you always need to plan so that your cached data no longer exists. Always follow a routine to retrieve data by external means when your cache does not have it in storage. Similarly, always check your cache before retrieving data from the outside. The goal of the cache is to reduce network activity, lengthy processes, and provide a flexible user interface in your application. So use it responsibly :)

+166
Apr 09 '12 at 6:20
source share

i The best way to clear the application cache at shutdown so that each cache timer is cleared when a new activity is called.

put this code in onDestroy () for a clean application cache

 @Override protected void onDestroy() { super.onDestroy(); try { trimCache(this); // Toast.makeText(this,"onDestroy " ,Toast.LENGTH_LONG).show(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void trimCache(Context context) { try { File dir = context.getCacheDir(); if (dir != null && dir.isDirectory()) { deleteDir(dir); } } catch (Exception e) { // TODO: handle exception } } public static boolean deleteDir(File dir) { if (dir != null && dir.isDirectory()) { String[] children = dir.list(); for (int i = 0; i < children.length; i++) { boolean success = deleteDir(new File(dir, children[i])); if (!success) { return false; } } } // The directory is now empty so delete it return dir.delete(); } 
+13
May 12 '12 at 6:40
source share

I think the idea behind the cache is to write whatever you want, and Android will control its size if it gets too tall.

You should keep in mind that you can write files to the cache, but always checks to see if the file is saved when you try to access it. And let the android manage the cache.

+1
Apr 02 2018-12-12T00:
source share

Depending on the type of application:

  • Some applications use only separate sessions and do not need to remember any data, so you can clear the cache whenever you want (some applications even do this automatically in their onStop activity)
  • Most applications store your data because they remember your settings, the account you used to log in ... In this case, it is best to clear the cache if you do not use the application much.

also:

 So i took a look at Chrome app (Galaxy Nexus) and the cache size for the application is 110 MB. But what wired is that applications like Google current & Google maps cache the content in something called (USB Storage Data) : 

AFAIK, Usb storage data is different from the cache: the storage is designed to store information about a specific program (for example, maps for the GPS application), the cache is used to store user information (for example, to enter the system)

In the case of google maps: I assume that they store the map data in the usb storage and save your settings and search history in the cache ==> the map data depends on the application, the settings and search history depend on the user

+1
Apr 02 2018-12-12T00:
source share

According to the documentation, the system will clear the cache when the device is in low internal storage . Since API8 you have the getExternalCacheDir () method , which I think is useful, as I read, you can have about 150 MB of data, but the drawback of the external cache is that you have to clear the cache directory yourself if it will get too big.

0
Apr 6 2018-12-12T00:
source share



All Articles