Search code examples
androidfilelifecycletemporary

Android Temporary file - Life cycle


What is the life cycle of Temporary file in Android?

Who is responsible for their clean up?


Solution

  • Eventually I found out that I have to do it by my self, so I am running this clear cache method each time I start my app.

    private static final long MIN_FREE_BYTES = 1024 * 1024 * 5; // this is 5M, Android recommend that there will always remind at last 1M
        public static void cleareCache(File directory){
            if(directory == null){
                directory = AppGenManager.getInstance().getCacheDir();
            }
            if(checkRemindingSpace(directory.getPath()) > MIN_FREE_BYTES){
                return;
            }
    
            File[] files = directory.listFiles();
            if (files != null) {
                for (File file : files){
                    if(file.isDirectory()){
                        cleareCache(file);
                    }
                    else{
                        file.delete();
                    }
                }
            }
        }
    
        /**
         * @param path file path
         * @return the number of available bytes on this directory
         */
        private static long checkRemindingSpace(String path){
            StatFs stat = new StatFs(path);
            long blockSize = stat.getBlockSize();
            long availableBlocks = stat.getAvailableBlocks();
            return availableBlocks * blockSize;
        }