Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why to use getCacheDir() on Android

Tags:

Android may auto-delete the files in CacheDir once the system gets low on memory. But the docs say we should not rely on the system clearing this cache, and hence write additional code for polling and deleting.

If this is the case, why should one choose getCacheDir() over getFilesDir()? Both are in-memory, and the latter offers more power to the developer in terms of what to clean up and when.

Thanks!

like image 446
dev Avatar asked Dec 05 '12 19:12

dev


2 Answers

Android may auto-delete the files in CacheDir once the system gets low on memory.

Correct. Third party apps can also delete files from apps' cache directories. And, as zapl notes, the user can manually clear an app's cache from Settings.

But the docs say we should not rely on the system clearing this cache, and hence write additional code for polling and deleting.

Also correct.

If this is the case, why should one opt getCacheDir() over getFileDir() ?

Because the OS, third-party apps, and the user can clear the cache. However, just because those things can clear the cache does not mean that they automatically will clear the cache, and so you need to tidy up your cache from time to time yourself. Similarly, while your mother can clean your room, it is generally a good idea if you clean your room yourself, if you don't want to be hit with a broom.

and the latter offers more power to the developer in terms of what to clean up and when...

No, it does not. getCacheDir() returns a File object. getFilesDir() returns a File object. They are equivalent in terms of "power to the developer in terms of what to clean up and when".

like image 68
CommonsWare Avatar answered Sep 23 '22 20:09

CommonsWare


getCacheDir() returns the path to the cache files whereas getFilesDir() returns the path to files created and stored in the internal storage of your app. The internal storage is persistent: it cannot be deleted by the system.

like image 38
znat Avatar answered Sep 24 '22 20:09

znat