Why to use getCacheDir() on Android

后端 未结 2 1196
自闭症患者
自闭症患者 2020-12-31 03:25

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 addi

相关标签:
2条回答
  • 2020-12-31 03:32

    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.

    0 讨论(0)
  • 2020-12-31 03:46

    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".

    0 讨论(0)
提交回复
热议问题