Android临时文件 - 生命周期

时间:2012-02-14 08:12:31

标签: android file lifecycle temporary

Android中临时文件的生命周期是什么?

谁负责清理?

1 个答案:

答案 0 :(得分:0)

最终我发现我必须自己做,所以每次启动应用程序时都会运行这种清除缓存方法。

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;
    }