如同行车记录仪一样,在磁盘空间不足的时候,循环删除最老的文件,释放磁盘空间,ARCH_DIR为需要清理的目录:
private void cleanFiles() {
new Thread(new Runnable() {
@Override
public void run() {
if (wakeLock != null) wakeLock.acquire();
try {
File dir = new File(ARCH_DIR);
File[] files = dir.listFiles();
double totalSpace = 1.0 * Environment.getExternalStorageDirectory().getTotalSpace();
if (files != null) {
for (File file : files) {
if (!file.exists()) continue;
double ratio = Environment.getExternalStorageDirectory().getFreeSpace() / totalSpace;
if (ratio > 0.3) break;
file.delete();
}
}
} finally {
if (wakeLock != null) wakeLock.release();
}
}
}).start();
}